package com.clwl.supervise.superviseapp.service.risk;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.risk.*;
import com.clwl.supervise.superviseapp.entity.risk.saveEntity.RiskDynamicVo;
import com.clwl.supervise.superviseapp.entity.risk.saveEntity.RiskStaticVo;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.*;
import com.clwl.supervise.superviseapp.mapper.risk.*;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.SequenceService;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.base.JgAllRiskLevelService;
import com.clwl.supervise.superviseapp.service.liability.LiabilityService;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.DoubleUtil;
import com.clwl.supervise.superviseapp.util.HolidayUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;


@Service
@Slf4j
public class RiskManagerService {


    @Resource
    private TsUserMapper tsUserMapper;
    //静态评定表
    @Resource
    private JgStaticScoringMapper staticScoringMapper;
    //静态分值评定项目
    @Resource
    private JgStaticProjectMapper staticProjectMapper;
    //静态分值评定参考分值
    @Resource
    private JgStaticScoreMapper staticScoreMapper;
    //异常
    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;
    //异常
    @Resource
    private JgDynamicContentMapper jgDynamicContentMapper;
    //整改
    @Resource
    private JgRectificationMapper rectificationMapper;
    //调查设置
    @Resource
    private JgInvestigationSetMapper jgInvestigationSetMapper;
    @Resource
    private JgRectificationContentMapper rectificationContentMapper;
    @Resource
    private JgInvestigationContentMapper investigationContentMapper;
    //调查
    @Resource
    private JgInvestigationMapper investigationMapper;
    //动态评定表评级
    @Resource
    private JgDynamicScoringMapper dynamicScoringMapper;
    //静态分值评定项目
    @Resource
    private JgDynamicContentMapper dynamicContentMapper;
    //静态分值评定标准表
    @Resource
    private JgDynamicStandardMapper dynamicStandardMapper;
    @Resource
    private JgDailyCheckMapper jgDailyCheckMapper;
    @Resource
    private JgRiskLevelResetInfoMapper riskLevelResetInfoMapper;
    @Resource
    private JgDailyStandardMapper jgDailyStandardMapper;
    @Resource
    private JgDailyContentMapper jgDailyContentMapper;
    @Resource
    private JgCompanyInwareMapper jgCompanyInwareMapper;
    @Resource
    private JgCheckMissingMapper jgCheckMissingMapper;
    @Resource
    private JgCheckProblemMapper jgCheckProblemMapper;
    @Resource
    private JgTemplateMapper templateMapper;
    //静态分值评定标准表
    @Resource
    private TcCompanyMapper companyMapper;
    @Resource
    private JgSpjyxkMapper jgSpjyxkMapper;
    @Resource
    private JgSpzcMapper jgSpzcMapper;
    //风险等级评定
    @Resource
    private JgRiskLevelMapper riskLevelMapper;

    @Resource
    private JgDsjMapper jgDsjYzwfsxmdMapper;
    //字典表
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    //监管环节
    @Resource
    private JgProcessCodeMapper jgProcessCodeMapper;
    //餐饮服务
    @Resource
    private JgClassifyCyfwMapper classifyCyfwMapper;
    //食品 销售
    @Resource
    private JgClassifySpxsMapper classifySpxsMapper;
    //食品生产
    @Resource
    private JgClassifySpscCompMapper classifySpscCompMapper;

    @Resource
    private JgRiskGradeMapper gradeMapper;

    @Resource
    private JgScDynamicScoringMapper scDynamicScoringMapper;
    @Resource
    private JgRiskGradeScoreMapper gradeScoreMapper;
    @Resource
    private JgRiskLevelDynamicMapper riskLevelDynamicMapper;
    @Resource
    private JgRiskDynamicTemplateMapper riskDynamicTemplateMapper;
    @Resource
    private JgDynamicCustomProjectMapper dynamicCustomProjectMapper;
    @Resource
    private JgDynamicCustomScoreMapper dynamicCustomScoreMapper;
    @Resource
    private JgCreditCustomProjectMapper creditCustomProjectMapper;
    @Resource
    private JgCreditCustomScoreMapper creditCustomScoreMapper;
    @Resource
    private JgStaticCustomProjectMapper staticCustomProjectMapper;
    @Resource
    private JgStaticCustomScoreMapper staticCustomScoreMapper;
    @Resource
    private JgRiskCheckContentMapper riskCheckContentMapper;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private TsDeptMapper tsDeptMapper;
    @Resource
    private JgClassifySpscCompMapper jgClassifySpscCompMapper;
    @Resource
    private JgDailyCheckSetMapper jgDailyCheckSetMapper;
    @Resource
    private LiabilityService liabilityService;
    @Resource
    private SequenceService sequenceService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    public JgAllRiskLevelService levelService;

    private final String PROCESS_SP = "spxs"; //食品销售
    private final String PROCESS_CY = "cyfw"; //餐饮服务
    private final String SOURCE_TYPE = "APP"; //来源类型
    private final String A_LEVEL = "A";
    private final String B_LEVEL = "B";

    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectCompanyPage(Integer pageNum, Integer pageSize, CommonSearchEntity params) {
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("1") < 0) {
            //用户监管范围不包含经营
            return new Page<>();
        }
        List<String> holidayList = HolidayUtil.getYearHolidays(DateUtil.year(new Date()));
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }
        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.setProcessList(processList);
        params.setYear(DateUtil.year(new Date()));
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        log.info("params:{}", params);
        if ("0".equals(params.getType())) {
            //风险评定
            Long total = staticScoringMapper.selectCompanyCount(params);
            iPage.setTotal(total);
            IPage<Map<String, Object>> page = staticScoringMapper.selectCompanyList(iPage, params);
            for (Map<String, Object> record : page.getRecords()) {
                Object fzrq = record.get("FZRQ");
                record.put("ADVENT_STATUS", "N");
                if (fzrq != null && !"".equals(fzrq)) {
                    String fzrqStr = fzrq.toString().replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "");
                    long days = HolidayUtil.getLastYearWorkdayDays(new Date(), DateUtil.parse(fzrqStr), holidayList);
                    //30天内做风险等级 剩余7天的时候提醒 就是法证日期距离当前时间已经过去23天了
                    if (days >= 23 && days <= 30) {
                        record.put("ADVENT_STATUS", "L");
                    }
                }
            }
            return page;
        } else {
         /*   //评级评分状态  如果为空  默认传入未评级  如果传入3  则为查询全部
            String checkStatus = params.getCheckStatus();
            if (StringUtils.isEmpty(checkStatus)){
                //默认参数为2
                params.setCheckStatus("2");
            }if ("3".equals(checkStatus)){
                //3为查询全部
                params.setCheckStatus(null);
            }*/
            //风险等级评定
            TsUser user = tsUserMapper.selectById(UserHelper.getUserId());
            Long total = riskLevelMapper.selectCompanyCount(params);
            iPage.setTotal(total);
            IPage<Map<String, Object>> companyList = riskLevelMapper.selectCompanyList(iPage, params);
            for (Map<String, Object> record : companyList.getRecords()) {
                record.put("AUDIT_AUTH", user.getType());
                Object fzrq = record.get("FZRQ");
                record.put("ADVENT_STATUS", "N");
                if (fzrq != null && !"".equals(fzrq)) {
                    String fzrqStr = fzrq.toString().replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "");
                    long days = HolidayUtil.getLastYearWorkdayDays(new Date(), DateUtil.parse(fzrqStr), holidayList);
                    //30天内做风险等级 剩余7天的时候提醒 就是法证日期距离当前时间已经过去23天了
                    if (days >= 23 && days <= 30) {
                        record.put("ADVENT_STATUS", "L");
                    }
                }
            }
            return companyList;
        }
    }

    /**
     * 获取静态评级的时候需要显示的信息
     *
     * @param companyId 企业id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getStaticContentInfo(Long companyId) throws IllegalAccessException {
        Map<String, Object> resultMap = new HashMap<>();

        String currentYear = DateUtil.format(new Date(), "yyyy"); // 统一年份格式
        String lockKey = "static_lock_" + companyId + "_" + currentYear; // 锁关联年份
        synchronized (lockKey.intern()) {
            Map<String, Object> companyMap = companyMapper.selectCompanyInspectionInfo(companyId);
            resultMap.put("companyId", companyId);
            resultMap.put("lngLat", companyMap.get("LNG_LAT"));
            resultMap.put("deptName", companyMap.get("DEPT_NAME"));
            resultMap.put("companyName", companyMap.get("COMPANY_NAME"));
            resultMap.put("companyAddress", companyMap.get("ADDRESS"));
            resultMap.put("companyType", companyMap.get("SUPERVISE_PROCESS")
                    + (companyMap.get("BUSINESS_TYPE") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE"))
                    + (companyMap.get("BUSINESS_TYPE_TWO") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE_TWO")));
            resultMap.put("businessScope", companyMap.get("BUSINESS_SCOPE"));
            resultMap.put("concat", companyMap.get("CONTACT"));
            resultMap.put("concatPhone", companyMap.get("CONTACT_PHONE"));
            resultMap.put("supProcess", companyMap.get("SUP_PROCESS"));
            resultMap.put("legalPerson", companyMap.get("LEGAL_PERSON"));
            //查询静态分值评定-异常原因 数据字典
            List<Map<String, Object>> dictList = getDictList();
            resultMap.put("abnormalReasonType", dictList);

            //通过companyId尝试获取今年的评分信息
            TcCompany company = companyMapper.selectById(companyId);
            JgStaticScoring staticScoring = inserStaticScoring(companyId, company, currentYear);
            resultMap.put("checkTime",  DateUtil.format(new Date(), "yyyy-MM-dd") );
            resultMap.put("totalScore", 0 );
            resultMap.put("checkStatus", staticScoring.getDeleteFlag());
            resultMap.put("companyPic", staticScoring.getComanyPic());

            if (staticScoring.getDeleteFlag() == 2L) {
                Long legalHead1Id = staticScoring.getScorePerson1Id() == null ? company.getLegalHead1Id() : staticScoring.getScorePerson1Id();
                Long legalHead2Id = staticScoring.getScorePerson2Id() == null ? company.getLegalHead2Id() : staticScoring.getScorePerson2Id();
                Long userId = UserHelper.getUserId();
                if (StringUtils.equals(legalHead1Id + "", legalHead2Id + "")) {
                    //防止监管人1中的存储的数据是监管人2 导致的两个监管人信息相同
                    legalHead2Id = company.getLegalHead1Id();
                }
                resultMap.put("scorePerson1Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead1Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead2Id : legalHead1Id));
                resultMap.put("scorePerson2Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead2Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead1Id : legalHead2Id));

            } else {
                resultMap.put("scorePerson1Id", staticScoring.getScorePerson1Id());
                resultMap.put("scorePerson2Id", staticScoring.getScorePerson2Id());

            }
            resultMap.put("manageStatus", staticScoring.getManageStatus() == null ? "0" : staticScoring.getManageStatus());
            resultMap.put("abnormalReason", staticScoring.getAbnormalReason());
            resultMap.put("abnormalCheckRecord", staticScoring.getAbnormalCheckRecord());
            resultMap.put("checkId", staticScoring.getId());
            resultMap.put("informUrl", staticScoring.getInformUrl());

            //检查项内容没有保存的时候还是查询整体模板
            List<JgStaticProject> childrenStaticProjectList = staticProjectMapper.selectStaticProjectList(company.getSupProcess(), company.getCompanyTypeId());
            childrenStaticProjectList = getTreeSortList(childrenStaticProjectList);
            if (childrenStaticProjectList.size() == 0) {
                //没有检查内容
                resultMap.put("totalScore", staticScoring == null ? 0 : ObjectUtils.defaultIfNull(staticScoring.getScoreTotal(), 0));
                return resultMap;
            }
            //创建一条今年的评分记录
            log.info("1-childrenStaticProjectList:{}", childrenStaticProjectList);
//            childrenStaticProjectList = generateList(childrenStaticProjectList);
            String remarks = "";
            for (JgStaticProject jgStaticProject : childrenStaticProjectList) {
                //这里查的是模版的 JgStaticScore 对象集合
                List<JgStaticScore> scoreList = staticScoreMapper.selectByProjectId(jgStaticProject.getId());
                List<Map<String, Object>> scoreMapList = new ArrayList<>();
                for (JgStaticScore jgStaticScore : scoreList) {

                    jgStaticScore.setText(jgStaticScore.getScoreName() + "(" + jgStaticScore.getScoreValue() + ")");
//                    jgStaticScore.setValue(String.valueOf(jgStaticScore.getId()));
                    jgStaticScore.setValue(jgStaticScore.getScoreValue());
                    // 取出业态备注信息
                    if (jgStaticProject.getRemarks() != null) {
                        remarks = jgStaticProject.getRemarks();
                    }
                    //改为map 形式返回数据，jgStaticScore 对象中 is_select 返回到前端会自动变成 _select
                    Map<String, Object> map = new HashMap<>();
                    // 获取obj的Class对象
                    Class<?> clazz = jgStaticScore.getClass();
                    // 获取类的所有字段
                    Field[] fields = clazz.getDeclaredFields();
                    // 遍历字段数组
                    for (Field field : fields) {
                        // 设置字段可访问（如果为private等修饰符）
                        field.setAccessible(true);
                        // 将字段名作为键，字段值作为值，存入map中
                        map.put(field.getName(), field.get(jgStaticScore));
                    }
                    scoreMapList.add(map);
                }
                // 这里把模版的 JgStaticScore 对象集合 赋值到 jgStaticProject 对象
                jgStaticProject.setScoreList(scoreList);
                jgStaticProject.setScoreMapList(scoreMapList);
            }
            resultMap.put("remarks", remarks);
            log.info("1转换完结果-childrenStaticProjectList:{}", childrenStaticProjectList);

            if (childrenStaticProjectList.isEmpty()) {
                System.out.println("没保存检查内容");
                childrenStaticProjectList.add(new JgStaticProject());
            }
            resultMap.put("projectList", childrenStaticProjectList);
        }
        log.info("resultMap:{}", resultMap);
        return resultMap;
    }

    /**
     * 获取静态评级的时候需要显示的信息
     *
     * @param staticScoringId 静态评分id
     * @return
     */
    @Transactional(readOnly = true)
    public Map<String, Object> getStaticContentResultInfo(Long staticScoringId) throws IllegalAccessException {
        Map<String, Object> resultMap = new HashMap<>();
        JgStaticScoring staticScoring = staticScoringMapper.selectById(staticScoringId);
        TcCompany company = companyMapper.selectById(staticScoring.getCompanyId());
        String currentYear = DateUtil.format(new Date(), "yyyy"); // 统一年份格式
        Map<String, Object> companyMap = companyMapper.selectCompanyInspectionInfo(staticScoring.getCompanyId());
        resultMap.put("companyId", staticScoring.getCompanyId());
        resultMap.put("lngLat", companyMap.get("LNG_LAT"));
        resultMap.put("deptName", companyMap.get("DEPT_NAME"));
        resultMap.put("companyName", companyMap.get("COMPANY_NAME"));
        resultMap.put("companyAddress", companyMap.get("ADDRESS"));
        resultMap.put("companyType", companyMap.get("SUPERVISE_PROCESS")
                + (companyMap.get("BUSINESS_TYPE") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE"))
                + (companyMap.get("BUSINESS_TYPE_TWO") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE_TWO")));
        resultMap.put("businessScope", companyMap.get("BUSINESS_SCOPE"));
        resultMap.put("concat", companyMap.get("CONTACT"));
        resultMap.put("concatPhone", companyMap.get("CONTACT_PHONE"));
        resultMap.put("supProcess", companyMap.get("SUP_PROCESS"));
        resultMap.put("legalPerson", companyMap.get("LEGAL_PERSON"));
        //查询静态分值评定-异常原因 数据字典
        resultMap.put("abnormalReasonType", getDictList());
        //通过companyId尝试获取今年的评分信息
        //查询有没有缓存的。有的话直接利用
        resultMap.put("checkTime", staticScoring.getScoreTime() == null ? DateUtil.format(new Date(), "yyyy-MM-dd") : staticScoring.getScoreTime());
        resultMap.put("totalScore", staticScoring.getScoreTotal() == null ? 0 : staticScoring.getScoreTotal());
        resultMap.put("checkStatus", staticScoring.getDeleteFlag());
        resultMap.put("companyPic", staticScoring.getComanyPic());
        resultMap.put("scorePerson1Id", staticScoring.getScorePerson1Id());
        resultMap.put("scorePerson2Id", staticScoring.getScorePerson2Id());

        resultMap.put("manageStatus", staticScoring.getManageStatus() == null ? "0" : staticScoring.getManageStatus());
        resultMap.put("abnormalReason", staticScoring.getAbnormalReason());
        resultMap.put("abnormalCheckRecord", staticScoring.getAbnormalCheckRecord());
        resultMap.put("checkId", staticScoring.getId());
        resultMap.put("informUrl", staticScoring.getInformUrl());
        //要评分的列表内容
        List<JgStaticProject> childrenStaticProjectList = staticProjectMapper.selectStaticProjectByScoringList(company.getSupProcess(), company.getCompanyTypeId(), staticScoring.getId());
        log.info("2-childrenStaticProjectList:{}", childrenStaticProjectList);
        childrenStaticProjectList = getTreeSortList(childrenStaticProjectList);
        String remarks = "";
        for (JgStaticProject jgStaticProject : childrenStaticProjectList) {
            jgStaticProject.setScoreValue(jgStaticProject.getScore());
            List<JgStaticScore> scoreList = staticScoreMapper.selectByProjectId(jgStaticProject.getId());
            List<Map<String, Object>> scoreMapList = new ArrayList<>();
            //各检查项分数，存在多选情况，将每个选中的分值相加
            for (JgStaticScore jgStaticScore : scoreList) {
                jgStaticScore.setText(jgStaticScore.getScoreName() + "(" + jgStaticScore.getScoreValue() + ")");
//                    jgStaticScore.setValue(String.valueOf(jgStaticScore.getId()));
                jgStaticScore.setValue(jgStaticScore.getScoreValue());
                if ("1".equals(jgStaticScore.getIsSelect())) {
                    jgStaticScore.set_selected(true);
                } else {
                    jgStaticScore.set_selected(false);
                }
                //改为map 形式返回数据，jgStaticScore 对象中 is_select 返回到前端会自动变成 _select
                Map<String, Object> map = new HashMap<>();
                // 获取obj的Class对象
                Class<?> clazz = jgStaticScore.getClass();
                // 获取类的所有字段
                Field[] fields = clazz.getDeclaredFields();
                // 遍历字段数组
                for (Field field : fields) {
                    // 设置字段可访问（如果为private等修饰符）
                    field.setAccessible(true);
                    // 将字段名作为键，字段值作为值，存入map中
                    map.put(field.getName(), field.get(jgStaticScore));
                }
                scoreMapList.add(map);
                //累加分数 将选中的各项分值累加
                if ("1".equals(jgStaticScore.getIsSelect())) {
                    jgStaticProject.setScoreValue(jgStaticScore.getScoreValue());
                }
            }
            // 取出业态备注信息
            if (jgStaticProject.getRemarks() != null) {
                remarks = jgStaticProject.getRemarks();
            }
            //如果没有选择某项  则不返回此对象 不然返回0分 会导致前端默认选中 选项值为0 的 数据
            jgStaticProject.setScoreList(scoreList);
            jgStaticProject.setScoreMapList(scoreMapList);
        }
        resultMap.put("remarks", remarks);
        log.info("2转换完结果-childrenStaticProjectList:{}", childrenStaticProjectList);

        if (childrenStaticProjectList.isEmpty()) {
            System.out.println("没保存检查内容");
            childrenStaticProjectList.add(new JgStaticProject());
        }
        resultMap.put("projectList", childrenStaticProjectList);

        log.info("resultMap:{}", resultMap);
        return resultMap;
    }


    public JgStaticScoring inserStaticScoring(Long companyId, TcCompany company, String currentYear) {
        JgStaticScoring staticScoring = new JgStaticScoring();
        staticScoring.setCompanyId(company.getId());
        staticScoring.setCompanyName(company.getCompanyName());
        staticScoring.setCreditCode(company.getCreditCode());
        staticScoring.setLicense(company.getLicense());
        staticScoring.setScoreYear(currentYear);
        staticScoring.setDeptId(UserHelper.getUserInfo().getDeptId());
        staticScoring.setDeptName(UserHelper.getUserInfo().getDeptName());
        staticScoring.setCheckPerson1Id(company.getLegalHead1Id());//当前登陆人
        staticScoring.setCheckPerson1Name(company.getLegalHead1Name());
        staticScoring.setCheckPerson2Id(company.getLegalHead2Id());
        staticScoring.setCheckPerson2Name(company.getLegalHead2Name());
        staticScoring.setScorePerson1Id(UserHelper.getUserId());//默认当前登陆人
        staticScoring.setScorePerson1Name(UserHelper.getUserInfo().getName());
        staticScoring.setManageStatus(company.getManageStatus());
        staticScoring.setCreateTime(new Date());
        staticScoring.setDeleteFlag(2L);
        staticScoring.setCreatorId(UserHelper.getUserId());
        staticScoring.setCreator(UserHelper.getUserInfo().getName());
        staticScoring.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
        staticScoring.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
        return staticScoring;
    }

    /**
     * 获取数据字典列表
     *
     * @return
     */
    public List<Map<String, Object>> getDictList() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        //查询静态分值评定-异常原因 数据字典
        List<SysDictData> dictDataList = sysDictDataMapper.selectByDictTypeCode("abnormal_reason_type");
        if (dictDataList != null && dictDataList.size() > 0) {
            for (SysDictData data : dictDataList) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", data.getDictLabel());
                map.put("text", data.getDictLabel());
                mapList.add(map);

            }
        }
        return mapList;
    }

    /**
     * 生成检查内容数据
     *
     * @param dataList
     * @return
     */
    public static List<JgStaticProject> generateList(List<JgStaticProject> dataList) {
        List<JgStaticProject> result = new ArrayList<>();
        for (JgStaticProject data : dataList) {
            String name = generateName(data, dataList);
            data.setProjectName(name);
            result.add(data);
        }
        return result;
    }

    /**
     * 生成父级名称拼接
     *
     * @param data
     * @param dataList
     * @return
     */
    public static String generateName(JgStaticProject data, List<JgStaticProject> dataList) {
        String name = data.getProjectName();
        Long parentId = data.getParentId();
        if (parentId != null) {
            for (JgStaticProject parentData : dataList) {
                Long id = parentData.getId();
                if (Objects.equals(id, parentId)) {
                    name = generateName(parentData, dataList) + "-" + name;
                    break;
                }
            }
        }
        return name;
    }

    /**
     * 取出叶子节点并排序,并将父级项目名称拼接到子级项目名称
     *
     * @return
     */
    public static List<JgStaticProject> getTreeSortList(List<JgStaticProject> toSortList) {
        List<JgStaticProject> sortList = new ArrayList<>();
        for (JgStaticProject project : toSortList) {
            //首先找出集合中的顶级数据，也就是 parentId 为 null 的数据
            if (project.getParentId() == null) {
                // 查找子级数据
                getChildDate(project, toSortList, sortList);
            }
        }
        return sortList;
    }


    public static void getChildDate(JgStaticProject parent, List<JgStaticProject> toSortList, List<JgStaticProject> sortList) {
        boolean hasChild = false;
        for (JgStaticProject child : toSortList) {
            if (Objects.equals(parent.getId(), child.getParentId())) {
                child.setProjectName(parent.getProjectName() + "-" + child.getProjectName());
                getChildDate(child, toSortList, sortList);
                hasChild = true;
            }
        }
        //如果没有子节点 则加入集合
        if (!hasChild) {
            sortList.add(parent);
        }
    }

    /**
     * 上传门头照
     *
     * @param checkId 检查Id
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public JgStaticScoring uploadStaticCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgStaticScoring staticScoring = staticScoringMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.risk.getPath());
        staticScoring.setComanyPic(fileEntity.getFilePath());
        staticScoringMapper.updateById(staticScoring);
        return staticScoring;
    }

    /**
     * 保存告知单
     *
     * @param checkId    评分id
     * @param informFile 告知单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveCheckInform(Long checkId, String informFile) {
        JgStaticScoring staticScoring = staticScoringMapper.selectById(checkId);
        if (staticScoring == null) {
            throw new RuntimeException("请先在保存页面内容再进行操作");
        }
        try {
            FileResultEntity informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.risk.getPath());
            staticScoring.setInformUrl(informFileUrl.getFilePath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单文件失败！");
        }
        staticScoringMapper.updateById(staticScoring);
        return staticScoring.getInformUrl();
    }

    /**
     * 保存评分信息
     *
     * @param temporarily  1临时 ；0正式保存
     * @param riskStaticVo 存储信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRiskStaticCheck(RiskStaticVo riskStaticVo, String temporarily) {
        synchronized ((riskStaticVo.getCompanyId()+"").intern()) {
            JgStaticScoring staticScoring = new JgStaticScoring();
            staticScoring.setCompanyId(riskStaticVo.getCompanyId());
            TcCompany company = companyMapper.selectById(staticScoring.getCompanyId());
            staticScoring.setCompanyName(company.getCompanyName());
            staticScoring.setCreditCode(company.getCreditCode());
            staticScoring.setLicense(company.getLicense());
            staticScoring.setScorePerson1Id(riskStaticVo.getScorePerson1Id());
            staticScoring.setCheckPerson1Id(riskStaticVo.getScorePerson1Id());
            TsUser scorePerson1Name = tsUserMapper.selectById(riskStaticVo.getScorePerson1Id());
            if (scorePerson1Name != null) {
                staticScoring.setScorePerson1Name(scorePerson1Name.getName());
                staticScoring.setCheckPerson1Name(scorePerson1Name.getName());
            }
            staticScoring.setScorePerson2Id(riskStaticVo.getScorePerson2Id());
            staticScoring.setCheckPerson2Id(riskStaticVo.getScorePerson2Id());
            TsUser scorePerson2Name = tsUserMapper.selectById(riskStaticVo.getScorePerson2Id());
            if (scorePerson2Name != null) {
                staticScoring.setScorePerson2Name(scorePerson2Name.getName());
                staticScoring.setCheckPerson2Name(scorePerson2Name.getName());
            }
            staticScoring.setManageStatus(riskStaticVo.getManageStatus());
            staticScoring.setDelayRating("1");   //页面没有
            //评分年
            staticScoring.setScoreYear(DateUtil.format(new Date(), "yyyy"));
            staticScoring.setCreateTime(new Date());
            staticScoring.setDeptId(UserHelper.getUserInfo().getDeptId());
            staticScoring.setDeptName(UserHelper.getUserInfo().getDeptName());
            staticScoring.setCreatorId(UserHelper.getUserId());
            staticScoring.setCreator(UserHelper.getUserInfo().getName());
            staticScoring.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            staticScoring.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
            staticScoring.setScoreTotal(riskStaticVo.getTotalScore());
            staticScoring.setAbnormalTime(riskStaticVo.getAbnormalTime());
            staticScoring.setAbnormalReason(riskStaticVo.getAbnormalReason());
            staticScoring.setAbnormalCheckRecord(riskStaticVo.getAbnormalCheckRecord());
            staticScoring.setScoreTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            staticScoring.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            staticScoring.setDeleteFlag(0L);
            staticScoringMapper.insert(staticScoring);
            //boolean updateStatus = false;
            if (StringUtils.isNotBlank(riskStaticVo.getConcat())) {
                // updateStatus = true;
                company.setContact(riskStaticVo.getConcat());
            }
            if (StringUtils.isNotBlank(riskStaticVo.getConcatPhone())) {
                //updateStatus = true;
                company.setContactPhone(riskStaticVo.getConcatPhone());
            }
            if (StringUtils.isNotBlank(riskStaticVo.getLegalPerson())) {
                //updateStatus = true;
                company.setLegalPerson(riskStaticVo.getLegalPerson());
            }
            company.setStaticScoreStatus("1");
            company.setStaticScoreId(staticScoring.getId());
            companyMapper.updateById(company);


            try {
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("保存评分失败");
            }
            try {
                Map<Long, Long> parentMap = new HashMap<>();
                for (JgStaticProject jgStaticProject : riskStaticVo.getProjectList()) {
                    JgStaticProject newJgStaticProject = new JgStaticProject();
                    BeanUtil.copyProperties(jgStaticProject, newJgStaticProject, "id", "isTemplate", "staticScoringId");
                    newJgStaticProject.setIsTemplate("0");
                    newJgStaticProject.setStaticScoringId(staticScoring.getId());
                    //如果父级id 不为空 则取出 parentMap 中 模版检查项父级对应的 企业检查项
                    if (jgStaticProject.getParentId() != null) {
                        newJgStaticProject.setParentId(parentMap.get(jgStaticProject.getParentId()));
                    }
                    staticProjectMapper.insert(newJgStaticProject);
                    //将模版 与 企业 检查项id 一一对应 封装进map中 为子级检查项提供选择 需要保证保存顺序是 先存父级 再存子级
                    parentMap.put(jgStaticProject.getId(), newJgStaticProject.getId());
                    //List<JgStaticScore> staticScoreList = staticScoreMapper.selectByProjectId(jgStaticProject.getId());
                    for (JgStaticScore jgStaticScore : jgStaticProject.getScoreList()) {
                        JgStaticScore newJgStaticScore = new JgStaticScore();
                        BeanUtil.copyProperties(jgStaticScore, newJgStaticScore, "id", "staticProjectId");
                        newJgStaticScore.setStaticProjectId(newJgStaticProject.getId());
                        staticScoreMapper.insert(newJgStaticScore);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("保存分值失败");
            }
        }
    }

    /**
     * 获取上一年的评分
     *
     * @param checkId
     */
    @Transactional(readOnly = true)
    public Map<String, Object> getRiskStaticLastYearCheck(Long companyId) throws IllegalAccessException {
        JgStaticScoring lastYearStaticScoring = staticScoringMapper.selectByCompanyId(companyId, DateUtil.year(DateUtils.addYears(new Date(), -1)) + "", "0");
        if (lastYearStaticScoring != null) {
            return getRiskStaticYearList(lastYearStaticScoring);
        } else {
            return null;
        }
    }


    public Map<String, Object> getRiskStaticYearList(JgStaticScoring staticScoring) throws IllegalAccessException {
        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> companyMap = companyMapper.selectCompanyInspectionInfo(staticScoring.getCompanyId());
        TcCompany company = companyMapper.selectById(staticScoring.getCompanyId());
        resultMap.put("companyId", staticScoring.getCompanyId());
        resultMap.put("lngLat", companyMap.get("LNG_LAT"));
        resultMap.put("deptName", companyMap.get("DEPT_NAME"));
        resultMap.put("companyName", companyMap.get("COMPANY_NAME"));
        resultMap.put("companyAddress", companyMap.get("ADDRESS"));
        resultMap.put("companyType", companyMap.get("SUPERVISE_PROCESS")
                + (companyMap.get("BUSINESS_TYPE") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE"))
                + (companyMap.get("BUSINESS_TYPE_TWO") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE_TWO")));
        resultMap.put("businessScope", companyMap.get("BUSINESS_SCOPE"));
        resultMap.put("concat", companyMap.get("CONTACT"));
        resultMap.put("concatPhone", companyMap.get("CONTACT_PHONE"));
        resultMap.put("supProcess", companyMap.get("SUP_PROCESS"));
        resultMap.put("checkTime", DateUtil.format(new Date(), "yyyy-MM-dd"));
        resultMap.put("totalScore", staticScoring.getScoreTotal() == null ? 0 : staticScoring.getScoreTotal());
        resultMap.put("checkStatus", "2");
        resultMap.put("companyPic", staticScoring.getComanyPic());
        String legalHead1Id = staticScoring.getScorePerson1Id() == null ? company.getLegalHead1Id() + "" : staticScoring.getScorePerson1Id().toString();
        String legalHead2Id = staticScoring.getScorePerson2Id() == null ? company.getLegalHead2Id() + "" : staticScoring.getScorePerson2Id().toString();
        if (company.getLegalHead1Id() != null && StringUtils.equals(legalHead1Id.toString(), legalHead2Id.toString())) {
            //防止监管人1中的存储的数据是监管人2 导致的两个监管人信息相同
            legalHead2Id = company.getLegalHead1Id().toString();
        }
        Long userId = UserHelper.getUserId();
//        resultMap.put("scorePerson1Id", legalHead1Id.equals(userId) ? legalHead1Id : userId);
//        resultMap.put("scorePerson2Id", legalHead2Id.equals(userId) ? legalHead2Id : userId);
        resultMap.put("scorePerson1Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead1Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead2Id : legalHead1Id));
        resultMap.put("scorePerson2Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead2Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead1Id : legalHead2Id));
        resultMap.put("manageStatus", staticScoring.getManageStatus() == null ? "0" : staticScoring.getManageStatus());
        resultMap.put("abnormalReason", staticScoring.getAbnormalReason());
        resultMap.put("abnormalCheckRecord", staticScoring.getAbnormalCheckRecord());
        resultMap.put("checkId", staticScoring.getId());
        resultMap.put("informUrl", staticScoring.getInformUrl());
        String remarks = "";
        //查询静态评分检查项
        List<JgStaticProject> jgStaticProjects = staticProjectMapper.selectStaticProjectByScoringList(company.getSupProcess(), company.getCompanyTypeId(), staticScoring.getId());
        if (!jgStaticProjects.isEmpty()) {
            jgStaticProjects = getTreeSortList(jgStaticProjects);
            for (JgStaticProject jgStaticProject : jgStaticProjects) {
                List<JgStaticScore> scoreList = staticScoreMapper.selectByProjectId(jgStaticProject.getId());
                List<Map<String, Object>> scoreMapList = new ArrayList<>();

                //各检查项分数，存在多选情况，将每个选中的分值相加
                for (JgStaticScore jgStaticScore : scoreList) {
                    jgStaticScore.setText(jgStaticScore.getScoreName() + "(" + jgStaticScore.getScoreValue() + ")");
                    jgStaticScore.setValue(jgStaticScore.getScoreValue());
                    jgStaticScore.set_selected("1".equals(jgStaticScore.getIsSelect()));
                    //改为map 形式返回数据，jgStaticScore 对象中 is_select 返回到前端会自动变成 _select
                    Map<String, Object> map = new HashMap<>();
                    // 获取obj的Class对象
                    Class<?> clazz = jgStaticScore.getClass();
                    // 获取类的所有字段
                    Field[] fields = clazz.getDeclaredFields();
                    // 遍历字段数组
                    for (Field field : fields) {
                        // 设置字段可访问（如果为private等修饰符）
                        field.setAccessible(true);
                        // 将字段名作为键，字段值作为值，存入map中
                        map.put(field.getName(), field.get(jgStaticScore));
                    }
                    scoreMapList.add(map);
                    //累加分数 将选中的各项分值累加
                    if ("1".equals(jgStaticScore.getIsSelect())) {
                        jgStaticProject.setScoreValue(jgStaticScore.getScoreValue());
                    }
                    // 取出业态备注信息
                    if (jgStaticProject.getRemarks() != null) {
                        remarks = jgStaticProject.getRemarks();
                    }

                }
                //如果没有选择某项  则不返回此对象 不然返回0分 会导致前端默认选中 选项值为0 的 数据
                jgStaticProject.setScoreList(scoreList);
                jgStaticProject.setScoreMapList(scoreMapList);

            }
            resultMap.put("remarks", remarks);
            log.info("2转换完结果-childrenStaticProjectList:{}", jgStaticProjects);
        }
        resultMap.put("projectList", jgStaticProjects);
        log.info("resultMap:{}", resultMap);
        return resultMap;
    }


    /**
     * 静态评分沿用上一年
     *
     * @param checkId
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRiskStaticLastYearCheck(String checkId, Long scorePerson1Id, Long scorePerson2Id) {
        JgStaticScoring currentStaticScoring = staticScoringMapper.selectById(checkId);
        JgStaticScoring lastYearStaticScoring = staticScoringMapper.selectByCompanyId(currentStaticScoring.getCompanyId(), DateUtil.format(DateUtils.addYears(new Date(), -1), "yyyy"), "0");
        if (lastYearStaticScoring == null) {
            throw new RuntimeException("没有上一年的评分记录");
        } else {
            JgStaticScoring newScoring = staticScoringMapper.selectByCompanyId(currentStaticScoring.getCompanyId(), DateUtil.format(new Date(), "yyyy"), "0");
            newScoring = (newScoring == null ? new JgStaticScoring() : newScoring);
            BeanUtils.copyProperties(currentStaticScoring, newScoring);
            newScoring.setScoreTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            newScoring.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            try {
                newScoring.setScorePerson1Id(scorePerson1Id);
                newScoring.setScorePerson1Name(tsUserMapper.selectById(scorePerson1Id).getName());
                newScoring.setScorePerson2Id(scorePerson2Id);
                newScoring.setScorePerson2Name(tsUserMapper.selectById(scorePerson2Id).getName());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("获取不到所选择的评分人信息");
            }
            newScoring.setManageStatus(lastYearStaticScoring.getManageStatus());
            newScoring.setDelayRating(lastYearStaticScoring.getDelayRating());
            newScoring.setScoreTotal(lastYearStaticScoring.getScoreTotal());
            newScoring.setDeleteFlag(0L);
            staticScoringMapper.insert(newScoring);

            TcCompany tcCompany = companyMapper.selectById(currentStaticScoring.getCompanyId());
            tcCompany.setStaticScoreStatus("1");
            tcCompany.setStaticScoreId(newScoring.getId());
            companyMapper.updateById(tcCompany);
            //复制添加静态评分检查项
            insertStaticProjectInfo(lastYearStaticScoring.getId(), newScoring.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertStaticProjectInfo(Long id, Long scoringId) {
        List<JgStaticProject> projectTreeList = staticProjectMapper.findProjectTreeList(id);
        if (!projectTreeList.isEmpty()) {
            for (JgStaticProject project : projectTreeList) {
                JgStaticProject newProject = new JgStaticProject();
                BeanUtils.copyProperties(project, newProject);
                newProject.setStaticScoringId(scoringId);
                staticProjectMapper.insert(newProject);
                List<JgStaticScore> scoreList = project.getScoreList();
                //保存静态评分项的评分内容
                saveStaticScore(newProject.getId(), scoreList);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveStaticScore(Long projectId, List<JgStaticScore> scoreEntityList) {
        if (!scoreEntityList.isEmpty()) {
            for (JgStaticScore score : scoreEntityList) {
                JgStaticScore newScore = new JgStaticScore();
                BeanUtils.copyProperties(score, newScore);
                newScore.setStaticProjectId(projectId);
                staticScoreMapper.insert(newScore);
            }
        }
    }

//--------------------------------------------------------------------初次动态评分-----------------------------------------------------------------

    /**
     * @param companyId
     * @return
     */
    public Map<String, Object> getDynamicContentInfo(Long companyId) {

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> companyMap = companyMapper.selectCompanyInspectionInfo(companyId);
        if (!("spsc".equals(ObjectUtils.defaultIfNull(companyMap.get("SUP_PROCESS"), "")) || "tssc".equals(ObjectUtils.defaultIfNull(companyMap.get("SUP_PROCESS"), "")))
                && companyMap.get("COMPANY_TYPE_ID") == null) {
            throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
        }

        String supProcess = ObjectUtils.defaultIfNull(companyMap.get("SUP_PROCESS"), "").toString();
        JgDynamicScoring dynamicScoring = null;

        resultMap.put("companyId", companyId);
        resultMap.put("lngLat", companyMap.get("LNG_LAT"));
        resultMap.put("deptName", companyMap.get("DEPT_NAME"));
        resultMap.put("companyName", companyMap.get("COMPANY_NAME"));
        resultMap.put("companyAddress", companyMap.get("ADDRESS"));
        resultMap.put("companyType", companyMap.get("SUPERVISE_PROCESS")
                + (companyMap.get("BUSINESS_TYPE") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE"))
                + (companyMap.get("BUSINESS_TYPE_TWO") == null ? "" : "/" + companyMap.get("BUSINESS_TYPE_TWO")));
        resultMap.put("businessScope", companyMap.get("BUSINESS_SCOPE"));
        resultMap.put("concat", companyMap.get("CONTACT"));
        resultMap.put("concatPhone", companyMap.get("CONTACT_PHONE"));
        resultMap.put("legalPerson", companyMap.get("LEGAL_PERSON"));
        resultMap.put("supProcess", companyMap.get("SUP_PROCESS"));


        //通过companyId尝试获取今年的评分信息
        dynamicScoring = dynamicScoringMapper.selectByCreatorCompanyId(companyId);

        if (dynamicScoring == null) {
            //创建一个默认的动态风险评分信息
            JgTemplate template = templateMapper.selectBySupProcess(supProcess, companyMap.get("COMPANY_TYPE_ID") == null ? null : Long.parseLong(companyMap.get("COMPANY_TYPE_ID").toString()), "3");
            if (template == null) {
                throw new RuntimeException("没有可用模板信息");
            }
            try {
                dynamicScoring = createDynamicScoring(companyId, template.getId());
            } catch (Exception e) {
                throw new RuntimeException("生成页面信息失败");
            }
            log.info("创建新的动态评分记录:{}", dynamicScoring);
        }
        try {
            resultMap.put("checkTime", dynamicScoring.getScoreTime() == null ? DateUtil.format(new Date(), "yyyy-MM-dd") : dynamicScoring.getScoreTime());
            resultMap.put("companyPic", dynamicScoring.getComanyPic());
            Long userId = UserHelper.getUserInfo().getId();
            Long legalHead1Id = dynamicScoring.getScorePerson1Id() == null ? (ObjectUtils.isNotEmpty(companyMap.get("LEGAL_HEAD1_ID")) ? Long.parseLong(companyMap.get("LEGAL_HEAD1_ID").toString()) : null) : dynamicScoring.getScorePerson1Id();
            Long legalHead2Id = dynamicScoring.getScorePerson2Id() == null ? (ObjectUtils.isNotEmpty(companyMap.get("LEGAL_HEAD2_ID")) ? Long.parseLong(companyMap.get("LEGAL_HEAD2_ID").toString()) : null) : dynamicScoring.getScorePerson2Id();
            if (StringUtils.equals(legalHead1Id + "", legalHead2Id + "")) {
                //防止监管人1中的存储的数据是监管人2 导致的两个监管人信息相同
                legalHead2Id = (ObjectUtils.isNotEmpty(companyMap.get("LEGAL_HEAD1_ID")) ? Long.parseLong(companyMap.get("LEGAL_HEAD1_ID").toString()) : null);
            }
            resultMap.put("scorePerson1Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead1Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead2Id : legalHead1Id));
            resultMap.put("scorePerson2Id", StringUtils.equals(userId + "", legalHead1Id + "") ? legalHead2Id : (StringUtils.equals(userId + "", legalHead2Id + "") ? legalHead1Id : legalHead2Id));
            resultMap.put("manageStatus", dynamicScoring.getManageStatus() == null ? "0" : dynamicScoring.getManageStatus());
            resultMap.put("abnormalReason", dynamicScoring.getAbnormalReason());
            resultMap.put("resultTime", dynamicScoring.getResultTime());
            resultMap.put("abnormalCheckRecord", dynamicScoring.getAbnormalCheckRecord());
            resultMap.put("checkId", String.valueOf(dynamicScoring.getId()));
            resultMap.put("informUrl", dynamicScoring.getInformUrl());
            resultMap.put("checkResults", dynamicScoring.getCheckResults() == null ? "1" : dynamicScoring.getCheckResults());
            resultMap.put("copeResult", dynamicScoring.getCopeResult() == null ? "1" : dynamicScoring.getCopeResult());
            resultMap.put("otherProblem", dynamicScoring.getOtherProblem());
            resultMap.put("totalScore", dynamicScoring.getScoreTotal() == null ? 0 : dynamicScoring.getScoreTotal());
            resultMap.put("checkStatus", dynamicScoring.getDeleteFlag());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取信息失败");
        }
        //查看当前企业是否之前填写了检查信息
        try {
            //获取已经填写的检查内容
            //风险信息
            Map<String, String> riskMap = baseDataService.riskInfo(companyId);
            List<String> riskCode = new ArrayList<>();
            Set<String> riskKeySet = riskMap.keySet();
            for (String riskKey : riskKeySet) {
                if (!riskMap.get(riskKey).equals("0")) {
                    riskCode.add(riskKey);
                }
            }
            List<Map<String, Object>> checkMissingListAll = jgCheckMissingMapper.selectMapList();
            List<Map<String, Object>> checkProblemListAll = jgCheckProblemMapper.selectMapList();
            //标准列表
            List<Map<String, Object>> checkStandardList = jgDailyStandardMapper.selectDynamicStandardList(supProcess, companyMap.get("COMPANY_TYPE_ID") == null ? null : Long.parseLong(companyMap.get("COMPANY_TYPE_ID").toString()), dynamicScoring.getId());
            List<String> templateStandardList = new ArrayList<>();
            for (Map<String, Object> checkStandard : checkStandardList) {
                //获取标准中检查内容TEPLATE_STANDARD_ID
                //log.info("已经存在的检查结果获取历史检查数据,TEPLATE_STANDARD_ID:{},DYNAMIC_SCORING_ID:{}", checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DYNAMIC_SCORING_ID"));
                List<Map<String, Object>> contentList = jgDailyContentMapper.selectDynamicByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DYNAMIC_SCORING_ID"), riskCode);
                //jgDailyContentMapper.selectDynamicByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DYNAMIC_SCORING_ID"), riskCode);
                for (Map<String, Object> content : contentList) {
                    //获取合理缺项
                    List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    //List<Map<String, Object>> checkMissingList = jgCheckMissingMapper.selectByContentId(content.get("ID"));
                    for (Map<String, Object> map : checkMissingList) {
                        map.put("is_selected", false);
                        if (content.get("MISSING_ITEM_CONTENT") != null) {
                            if (String.valueOf(content.get("MISSING_ITEM_CONTENT")).equals(String.valueOf(map.get("describe")))) {
                                map.put("is_selected", true);
                            }
                        }
                    }

                    content.put("checkMissingList", checkMissingList);
                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    // List<Map<String, Object>> checkProblemList = jgCheckProblemMapper.selectByContentId(content.get("ID"));
                    if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (content.get("PROBLEM_CONTENT") != null) {
                                String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    content.put("checkProblemList", checkProblemList);
                }
                checkStandard.put("contentList", contentList);
            }
            resultMap.put("projectList", checkStandardList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取检查信息失败!");
        }
        log.info("resultMap:{}", resultMap);
        return resultMap;

    }

    /**
     * 创建动态评分信息
     *
     * @param companyId            企业id
     * @param companyMapper
     * @param dynamicScoringMapper
     * @param tsUserMapper
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDynamicScoring createDynamicScoring(Long companyId, Long templateId) {
        synchronized ((companyId + "").intern()) {
            JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectByCreatorCompanyId(companyId);
            dynamicScoring = (dynamicScoring == null ? new JgDynamicScoring() : dynamicScoring);
            TcCompany company = companyMapper.selectById(companyId);
            dynamicScoring.setCompanyId(companyId);
            dynamicScoring.setCompanyName(company.getCompanyName());
            dynamicScoring.setCreditCode(company.getCreditCode());
            dynamicScoring.setLicense(company.getLicense());
            dynamicScoring.setTemplateId(templateId);
            dynamicScoring.setScoreYear(DateUtil.format(new Date(), "yyyy"));
            dynamicScoring.setDeptId(UserHelper.getUserInfo().getDeptId());
            dynamicScoring.setDeptName(UserHelper.getUserInfo().getDeptName());
            try {
                if (company.getLegalHead1Id() != null) {
                    dynamicScoring.setCheckPerson1Id(company.getLegalHead1Id());
                    dynamicScoring.setCheckPerson1Name(tsUserMapper.selectById(company.getLegalHead1Id()).getName());
                }
                if (company.getLegalHead2Id() != null) {
                    dynamicScoring.setCheckPerson2Id(company.getLegalHead2Id());
                    dynamicScoring.setCheckPerson2Name(tsUserMapper.selectById(company.getLegalHead2Id()).getName());
                }
                dynamicScoring.setScorePerson1Id(UserHelper.getUserId());
                dynamicScoring.setScorePerson1Name(UserHelper.getUserInfo().getName());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("获取执法人员信息失败");
            }
            dynamicScoring.setManageStatus("0");
            dynamicScoring.setDelayRating("1");
            dynamicScoring.setScoreTotal(0D);
            dynamicScoring.setCreateTime(new Date());
            dynamicScoring.setCreatorId(UserHelper.getUserId());
            dynamicScoring.setCreator(UserHelper.getUserInfo().getName());
            dynamicScoring.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            dynamicScoring.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
            if (dynamicScoring.getId() == null) {
                dynamicScoring.setDeleteFlag(2L);
                dynamicScoringMapper.insert(dynamicScoring);
            }
            return dynamicScoring;
        }
    }


    /**
     * 上传门头照
     *
     * @param checkId 检查Id
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDynamicScoring uploadDynamicCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.risk.getPath());
        dynamicScoring.setComanyPic(fileEntity.getFilePath());
        dynamicScoringMapper.updateById(dynamicScoring);
        return dynamicScoring;
    }

    /**
     * 保存告知单
     *
     * @param checkId    评分id
     * @param informFile 告知单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDynamicScoring saveRiskDynamicCheckInform(Long checkId, String informFile) {
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(checkId);
        try {
            FileResultEntity informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.risk.getPath());
            dynamicScoring.setInformUrl(informFileUrl.getFilePath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单文件失败！");
        }
        dynamicScoringMapper.updateById(dynamicScoring);
        return dynamicScoring;
    }

    /**
     * 临时保存动态评分信息
     *
     * @param riskDunamicVo
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRiskDynamicCheck(RiskDynamicVo riskDunamicVo, RectificationSituationData liabilitySituation) {
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(riskDunamicVo.getCheckId());

        log.info("riskDunamicVo:{}", riskDunamicVo);
        dynamicScoring.setScorePerson1Id(riskDunamicVo.getScorePerson1Id());
        dynamicScoring.setCheckPerson1Id(riskDunamicVo.getScorePerson1Id());
        if (riskDunamicVo.getScorePerson1Id() != null) {
            TsUser user1 = tsUserMapper.selectById(riskDunamicVo.getScorePerson1Id());
            dynamicScoring.setScorePerson1Name(user1 == null ? "" : user1.getName());
            dynamicScoring.setCheckPerson1Name(user1 == null ? "" : user1.getName());
        }
        dynamicScoring.setScorePerson2Id(riskDunamicVo.getScorePerson2Id());
        dynamicScoring.setCheckPerson2Id(riskDunamicVo.getScorePerson2Id());
        if (riskDunamicVo.getScorePerson2Id() != null) {
            TsUser user2 = tsUserMapper.selectById(riskDunamicVo.getScorePerson2Id());
            dynamicScoring.setScorePerson2Name(user2 == null ? "" : user2.getName());
            dynamicScoring.setCheckPerson2Name(user2 == null ? "" : user2.getName());
        }
        dynamicScoring.setManageStatus(riskDunamicVo.getManageStatus());
        dynamicScoring.setDelayRating("0");
        dynamicScoring.setCheckResults(riskDunamicVo.getCheckResults());
        dynamicScoring.setOtherProblem(riskDunamicVo.getOtherProblem());
        dynamicScoring.setCopeResult(riskDunamicVo.getCopeResult());
        if (riskDunamicVo.getCopeResult().equals("1")){
            dynamicScoring.setResultTime("");
        }else {
            dynamicScoring.setResultTime(riskDunamicVo.getResultTime());
        }

        dynamicScoring.setAbnormalReason(riskDunamicVo.getAbnormalReason());
        dynamicScoring.setAbnormalTime(riskDunamicVo.getAbnormalTime());
        dynamicScoring.setAbnormalCheckRecord(riskDunamicVo.getAbnormalCheckRecord());
        //检查结果-重点项数量
        Long importentCount = 0L;
        //检查结果-重点项序号
        List<String> importentOrders = new ArrayList<>();
        //检查结果-一般项数量
        Long generalCount = 0L;
        //检查结果-一般项序号
        List<String> generalOrders = new ArrayList<>();
        Double scoreTotal = 0.0;

        // List<JgDynamicStandard> jgDynamicStandardList = dynamicStandardMapper.selectByDynamicScoringId(dynamicScoring.getId());
        // 1. 准备数据容器
        List<JgDynamicStandard> batchInsertStandards = new ArrayList<>();
        List<JgDynamicStandard> batchUpdateStandards = new ArrayList<>();
        List<JgDynamicContent> batchInsertContents = new ArrayList<>();
        List<JgDynamicContent> batchUpdateContents = new ArrayList<>();

        // 2. 构建标准映射关系（用于后续关联内容）
        Map<Pair<Long, Long>, JgDynamicStandard> standardMap = new HashMap<>();

        // 3. 先处理所有 Standards
        List<JgDynamicStandard> existingStandards = dynamicStandardMapper.selectByDynamicScoringId(dynamicScoring.getId());
        for (RiskDynamicVo.JgStandadMapVo vo : riskDunamicVo.getProjectList()) {
            // 查找或创建 Standard
            Optional<JgDynamicStandard> existing = existingStandards.stream()
                    .filter(s -> Objects.equals(s.getTemplateId(), vo.getTemplateId())
                            && Objects.equals(s.getStandardId(), vo.getId()))
                    .findFirst();

            JgDynamicStandard standard = existing.orElseGet(JgDynamicStandard::new);

            // 填充公共字段
            BeanUtils.copyProperties(vo, standard, "id"); // 使用BeanUtils简化字段复制
            standard.setName(vo.getStandardName());
            standard.setDynamicScoringId(dynamicScoring.getId());
            standard.setStandardId(vo.getId());

            // 设置创建信息（如果是新增）
            if (standard.getId() == null) {
                standard.setCreateTime(new Date());
                standard.setCreatorId(UserHelper.getUserId());
                standard.setCreator(UserHelper.getUserInfo().getName());
                standard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                standard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                standard.setDeleteFlag(0L);
                batchInsertStandards.add(standard);
            } else {
                batchUpdateStandards.add(standard);
            }

            // 保存映射关系（模板ID + 标准ID → Standard对象）
            standardMap.put(Pair.of(vo.getTemplateId(), vo.getId()), standard);
        }

        // 4. 批量保存 Standards（先插入后更新）
        if (!batchInsertStandards.isEmpty()) {
            dynamicStandardMapper.batchInsert(batchInsertStandards); // 需配置返回主键
        }
        if (!batchUpdateStandards.isEmpty()) {
            dynamicStandardMapper.batchUpdate(batchUpdateStandards);
        }

        // 5. 处理所有 Contents
        for (RiskDynamicVo.JgStandadMapVo vo : riskDunamicVo.getProjectList()) {
            if (vo.getContentList() == null) continue;

            // 获取关联的 Standard
            JgDynamicStandard standard = standardMap.get(Pair.of(vo.getTemplateId(), vo.getId()));

            // 查询现有 Contents
            List<JgDynamicContent> existingContents = dynamicContentMapper.selectByStandardId(standard.getId());
            Map<Long, JgDynamicContent> contentMap = existingContents.stream()
                    .collect(Collectors.toMap(JgDynamicContent::getContentId, c -> c));

            // 处理每个 Content
            for (RiskDynamicVo.ContentList content : vo.getContentList()) {
                JgDynamicContent dynamicContent = contentMap.containsKey(content.getId()) ?
                        contentMap.get(content.getId()) : new JgDynamicContent();

                // 填充公共字段
                BeanUtils.copyProperties(content, dynamicContent, "id");
                dynamicContent.setContentId(content.getId());
                dynamicContent.setDynamicStandardId(standard.getId());

                // 处理文件上传（仍需逐条处理）
                if (needUploadFile(content)) {
                    try {
                        FileResultEntity filePath = FileUploadUtil.uploadImageBase64Image(content.getProblemFile(), FileUploadEnum.risk.getPath());
                        dynamicContent.setProblemFile(filePath.getFilePath());
                    } catch (Exception e) {
                        log.error("保存失败!", e);
                    }
                }
                if ("1".equals(content.getImportentItem())) {
                    //一般项
                    generalCount = generalCount + 1;
                    generalOrders.add(content.getSerialNum() == null ? "" : content.getSerialNum().toString());
                } else if ("2".equals(content.getImportentItem())) {
                    //一般项
                    importentCount = importentCount + 1;
                    importentOrders.add(content.getSerialNum() == null ? "" : content.getSerialNum().toString());
                }

                if ("2".equals(content.getSelection())) {
                    scoreTotal += content.getScore();
                }
                // 收集保存操作
                if (dynamicContent.getId() == null) {
                    dynamicContent.setCreateTime(new Date());
                    dynamicContent.setCreatorId(UserHelper.getUserId());
                    dynamicContent.setCreator(UserHelper.getUserInfo().getName());
                    dynamicContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dynamicContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dynamicContent.setDeleteFlag(0L);
                    batchInsertContents.add(dynamicContent);
                } else {
                    batchUpdateContents.add(dynamicContent);
                }

            }
        }

        // 6. 批量保存 Contents
        if (!batchInsertContents.isEmpty()) {
            dynamicContentMapper.batchInsert(batchInsertContents);
        }
        if (!batchUpdateContents.isEmpty()) {
            dynamicContentMapper.batchUpdate(batchUpdateContents);
        }

        //临时保存不进行下面的操作
        TcCompany company = companyMapper.selectById(dynamicScoring.getCompanyId());
        //保存社会责任评分
        liabilityService.saveLiabilityStandard(dynamicScoring, liabilitySituation, company, dynamicScoring.getManageStatus());

        dynamicScoring.setScoreTotal(scoreTotal);
        dynamicScoring.setImportentCount(importentCount);
        dynamicScoring.setImportentOrders(String.join(",", importentOrders));
        dynamicScoring.setGeneralCount(generalCount);
        dynamicScoring.setGeneralOrders(String.join(",", generalOrders));
        dynamicScoringMapper.updateById(dynamicScoring);


    }

    /**
     * 最终保存
     *
     * @param riskDunamicVo
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRiskDynamicCheckOver(RiskDynamicVo riskDunamicVo, RectificationSituationData liabilitySituation) {
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(riskDunamicVo.getCheckId());

        if (StringUtils.equals(riskDunamicVo.getManageStatus(), "1")) {
            //经营异常保存的
            saveRiskDynamicCheck(riskDunamicVo, liabilitySituation);
        }

        dynamicScoring.setCreator(UserHelper.getUserInfo().getName());
        dynamicScoring.setCreatorId(UserHelper.getUserId());
        dynamicScoring.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        dynamicScoring.setDeleteFlag(0L);
        dynamicScoring.setScoreTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        dynamicScoring.setCreateTime(new Date());
        dynamicScoring.setScoreYear(DateUtil.year(new Date()) + "");
        dynamicScoring.setDeptId(UserHelper.getUserInfo().getDeptId());
        dynamicScoring.setDeptName(UserHelper.getUserInfo().getDeptName());
        dynamicScoring.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
        dynamicScoring.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
        dynamicScoringMapper.updateById(dynamicScoring);

        TcCompany company = companyMapper.selectById(dynamicScoring.getCompanyId());
        boolean updateStatus = false;
        if (StringUtils.isNotBlank(riskDunamicVo.getConcat())) {
            updateStatus = true;
            company.setContact(riskDunamicVo.getConcat());
        }
        if (StringUtils.isNotBlank(riskDunamicVo.getConcatPhone())) {
            updateStatus = true;
            company.setContactPhone(riskDunamicVo.getConcatPhone());
        }
        if (StringUtils.isNotBlank(riskDunamicVo.getLegalPerson())) {
            updateStatus = true;
            company.setLegalPerson(riskDunamicVo.getLegalPerson());
        }
        company.setDynamicScoreStauts("1");
        company.setDynamicScoreId(dynamicScoring.getId());
        companyMapper.updateById(company);

        //保存异常信息
        if ("1".equals(dynamicScoring.getManageStatus())) {
            saveEntAnomaly(company,
                    dynamicScoring, dynamicScoring.getAbnormalReason(), dynamicScoring.getAbnormalCheckRecord(), dynamicScoring.getResultTime(),
                    "", dynamicScoring.getCopeResult(), "2");

        }
        //如果选择的不是通过的话生成相应的后续步骤
        if ("2".equals(dynamicScoring.getCopeResult())) {
            //责令整改
            saveRectification(dynamicScoring.getResultTime(), company, dynamicScoring);
        } else if ("3".equals(dynamicScoring.getCopeResult())) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification(dynamicScoring.getResultTime(), company, dynamicScoring);

            //调查处理,查看调查处理开关是否打开
            JgInvestigationSet investigationSet = jgInvestigationSetMapper.selectByCheckTypeAndProcess("1", company.getSupProcess());
            //调查处理开关打开的情况下才生成下面的内容
            if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                saveInvestigation(company, dynamicScoring);
            }
        }

    }

    // 文件上传判断
    public boolean needUploadFile(RiskDynamicVo.ContentList content) {
        return StringUtils.isNotBlank(content.getProblemFile())
                && !"undefined".equals(content.getProblemFile())
                && content.getProblemFile().contains("data:image");
    }

    public void checkScoreStatus(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        //获取企业今年的静态评分分值
        if (StringUtils.equals(company.getStaticScoreStatus(), "2")) {
            throw new RuntimeException("该企业今年还未进行静态评分!");
        }
        if (StringUtils.equals(company.getDynamicScoreStauts(), "2")) {
            throw new RuntimeException("该企业还未进行动态评分!");
        }/*
        JgStaticScoring staticScoring = staticScoringMapper.selectByCompanyId(companyId, null, "0");
        if (staticScoring == null) {
            throw new RuntimeException("该企业今年还未进行静态评分!");
        }
        //获取企业初次动态评分分值
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.findJgDynamicScoringOverByCompanyId(companyId);
        if (dynamicScoring == null) {
            throw new RuntimeException("该企业还未进行初次动态评分!");
        }*/
    }

    /**
     * 保存调查处理
     *
     * @param company        企业信息
     * @param dynamicScoring 动态评分
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveInvestigation(TcCompany company, JgDynamicScoring dynamicScoring) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(dynamicScoring.getId(), "5");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(dynamicScoring.getId());
        investigation.setCheckType("5");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if (investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgDynamicContent> dailyContent = dynamicContentMapper.selectByDynamicCheckId(dynamicScoring.getId());
        if (!dailyContent.isEmpty()) {
            List<JgInvestigationContent> insertList = new ArrayList<>();
            for (JgDynamicContent jgDailyContent : dailyContent) {
                JgInvestigationContent investigationContent = new JgInvestigationContent();
                investigationContent.setInvestigationId(investigation.getId());
                investigationContent.setCheckType("5");
                investigationContent.setCheckContentId(jgDailyContent.getId());
                investigationContent.setCreateTime(new Date());
                investigationContent.setCreatorId(UserHelper.getUserId());
                investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
                investigationContent.setDeleteFlag(0L);
                investigationContent.setSerialNum(jgDailyContent.getStandardNum());
                investigationContent.setStandardName(jgDailyContent.getStandardName());
                investigationContent.setContentNum(jgDailyContent.getSerialNum());
                investigationContent.setCheckContent(jgDailyContent.getCheckContent());
                investigationContent.setSelection(jgDailyContent.getSelection());
                investigationContent.setProblemContent(jgDailyContent.getProblemContent());
                investigationContent.setProblemFile(jgDailyContent.getProblemFile());
                investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
                investigationContentMapper.insert(investigationContent);

                insertList.add(investigationContent);
            }

            // 批量插入
            investigationContentMapper.batchInsert(insertList);
        }
    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     * @param dynamicScoring         动态评分
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(String rectificationTimeLimit,
                                  TcCompany company, JgDynamicScoring dynamicScoring) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(dynamicScoring.getId(), "5");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(dynamicScoring.getId());
        rectification.setCheckType("5");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if (rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }

        //保存整改内容的初始信息
        if (!StringUtils.equals(dynamicScoring.getManageStatus(), "1")) {
            //选择的不是经营异常才存储这个问题项
            List<JgDynamicContent> dynamicContentList = dynamicContentMapper.selectByDynamicCheckId(dynamicScoring.getId());
            if (!dynamicContentList.isEmpty()) {
                List<JgRectificationContent> insertList = new ArrayList<>();
                for (JgDynamicContent dynamicContent : dynamicContentList) {
                    if ("2".equals(dynamicContent.getSelection())) {
                        JgRectificationContent rectificationContent = new JgRectificationContent();
                        rectificationContent.setRectificationId(rectification.getId());
                        rectificationContent.setCheckType("5");
                        rectificationContent.setCheckContentId(dynamicContent.getId());
                        rectificationContent.setCreateTime(new Date());
                        rectificationContent.setCreatorId(UserHelper.getUserId());
                        rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                        rectificationContent.setDeleteFlag(0L);
                        rectificationContent.setSerialNum(dynamicContent.getSerialNum());
                        rectificationContent.setStandardName(dynamicContent.getStandardName());
                        rectificationContent.setContentNum(dynamicContent.getSerialNum());
                        rectificationContent.setCheckContent(dynamicContent.getCheckContent());
                        rectificationContent.setSelection(dynamicContent.getSelection());
                        rectificationContent.setProblemContent("2".equals(dynamicContent.getSelection()) ? dynamicContent.getProblemContent() : null);
                        rectificationContent.setProblemFile(dynamicContent.getProblemFile());
                        rectificationContent.setMissingItemContent(dynamicContent.getMissingItemContent());
                        insertList.add(rectificationContent);
                    }
                }
                // 批量插入
                if (!insertList.isEmpty()) {
                    rectificationContentMapper.batchInsert(insertList);
                }
            }
        }
        // }

    }

    /**
     * 保存异常信息
     *
     * @param thjsEntAnomalyMapper
     * @param company              企业信息
     * @param dynamicScoring       动态评分
     * @param abnormalCause        异常原因
     * @param auditTrails          异常核查记录
     * @param rectifyTime          异常整改时间
     * @param checkResults         异常检查结果
     * @param exprocessResults     异常处理结果
     * @param temporary            等于2才是正式保存
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEntAnomaly(TcCompany company,
                               JgDynamicScoring dynamicScoring, String abnormalCause,
                               String auditTrails, String rectifyTime, String checkResults, String exprocessResults, String temporary) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dynamicScoring.getId(), "5");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("5");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(dynamicScoring.getId());
        jsEntAnomaly.setAbnormalCause(abnormalCause);
        jsEntAnomaly.setAuditTrails(auditTrails);
        jsEntAnomaly.setRectifyTime(rectifyTime);
        jsEntAnomaly.setCheckResults(checkResults);
        jsEntAnomaly.setProcessResults(exprocessResults);
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        //删除原来填写的检查内容信息，检查异常之后
        List<JgDynamicContent> dailyContentList = jgDynamicContentMapper.selectByDynamicCheckId(dynamicScoring.getId());

        int checkNum = 0;
        for (JgDynamicContent jgDynamicContent : dailyContentList) {
            jgDynamicContent.setSelection("2");
            checkNum = checkNum + 1;
        }
        jsEntAnomaly.setCheckNumber(checkNum);
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());

            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }

    }

    public Map<String, Object> getCheckResultInfo(Long dynamicScoringId) {
        Map<String, Object> result = new HashMap<>();
        //检查结果
        Map<String, Object> checkInfo = new HashMap<>();
        //获取和各项，不合格项，合理缺项比例
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(dynamicScoringId);
        List<JgDynamicContent> contentList = dynamicContentMapper.selectByDynamicCheckId(dynamicScoring.getId());
        int hege = 0;
        int buhege = 0;
        int heliquexiang = 0;

        if ("1".equals(dynamicScoring.getManageStatus())) {
            JsEntAnomaly entAnomaly = jsEntAnomalyMapper.selectByCheckId(dynamicScoring.getId(), "5");
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", entAnomaly == null ? "0" : entAnomaly.getCheckNumber());
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        } else {
            // is '选择项：1是、2否、3合理缺项'
            for (JgDynamicContent content : contentList) {
                String selection = content.getSelection();
                switch (selection) {
                    case "1":
                        hege++;
                        break;
                    case "2":
                        buhege++;
                        break;
                    case "3":
                        heliquexiang++;
                        break;
                }
            }
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", buhege);
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        }
        //动态评分
        checkInfo.put("SCORE_TOTAL", dynamicScoring.getScoreTotal());
        checkInfo.put("CHECK_RESULTS", dynamicScoring.getCheckResults());
        //处理结果：1通过检查，2责令整改，3调查处理
        checkInfo.put("PROCESS_RESULTS", dynamicScoring.getCopeResult());
        checkInfo.put("CHECK_PERSON1_NAME", dynamicScoring.getScorePerson1Name());
        checkInfo.put("CHECK_PERSON2_NAME", dynamicScoring.getScorePerson2Name());
        checkInfo.put("CHECK_DEPT_NAME", dynamicScoring.getDeptName());
        checkInfo.put("CHECK_DATE", dynamicScoring.getCheckTime());
        JgTemplate template = templateMapper.selectById(dynamicScoring.getTemplateId());
        if (template != null) {
            checkInfo.put("TEMPLATE_NAME", template.getName());
        }
        //整改完成时限 获取整改信息
        List<JgRectification> rectificationList = rectificationMapper.selectByCheckId(dynamicScoring.getId(), "5");
        checkInfo.put("RECTIFICATION_TIME_LIMIT", rectificationList.size() > 0 ? rectificationList.get(0).getRectificationTimeLimit() : "");
        //其他问题
        checkInfo.put("OTHER_PROBLEM", dynamicScoring.getOtherProblem());
        result.put("checkInfo", checkInfo);
        Map<String, Object> companyInfo = companyMapper.selectCompanyInspectionInfo(dynamicScoring.getCompanyId());
        companyInfo.put("MANAGE_STATUS", dynamicScoring.getManageStatus() == null ? "0" : dynamicScoring.getManageStatus());
        companyInfo.put("COMANY_PIC", dynamicScoring.getComanyPic());
        companyInfo.put("CHECK_TIME", dynamicScoring.getCheckTime());
        companyInfo.put("INFORM_URL", dynamicScoring.getInformUrl());
        result.put("baseInfo", companyInfo);
        List<Map<String, Object>> standardList = dynamicStandardMapper.selectMapByDynamicCheckId(dynamicScoring.getId());
        result.put("standardList", standardList);
        return result;
    }

    /**
     * 查询动态评分检查呢内容列表
     *
     * @param standardId 标准项id
     * @return
     */
    public List<JgDynamicContent> getRiskDynamicContentList(Long standardId) {
        return dynamicContentMapper.selectByStandardId(standardId);
    }

    //-------------------------------------------------------------------风险等级经营企业的评定或者是生产企业初次评定-------------------------------------------------------

    /**
     * 获取评定等级的基础信息和评分内容
     *
     * @param companyId 企业id
     * @return
     */

    public JgRiskLevel getRiskLevelInfo(Long riskLevelId) {
        //如果有之前未保存的 直接利用
        JgRiskLevel jgRiskLevel = riskLevelMapper.selectById(riskLevelId);
        TcCompany company = companyMapper.selectById(jgRiskLevel.getCompanyId());
        jgRiskLevel.setCompanyTypeTwoId(company.getCompanyTypeTwoId());
        jgRiskLevel.setCompanyTypeId(company.getCompanyTypeId());
//        jgRiskLevel.setIsShezuo(company.getIsShezuo());
        jgRiskLevel.setContactInformation(company.getContactPhone());
        jgRiskLevel.setCompanyAddress(company.getAddress());
        jgRiskLevel.setContacts(company.getContact());
        jgRiskLevel.setSupProcess(company.getSupProcess());
        //选择食用人群
        List<SysDictData> dictDataList = sysDictDataMapper.selectByDictTypeCode("risk_level_consumer");
        List<Map<String, Object>> consumerGroupList = new ArrayList<>();
        for (SysDictData sysDictData : dictDataList) {
            Map<String, Object> consumerGroup = new HashMap<>();
            consumerGroup.put("text", sysDictData.getDictLabel());
            consumerGroup.put("value", sysDictData.getDictValue());
            consumerGroupList.add(consumerGroup);
        }

        //获取企业的一级业态信息
        JgProcessCode processCode = jgProcessCodeMapper.selectByCode(company.getSupProcess());
        jgRiskLevel.setSupProcessName(processCode.getName());
        switch (company.getSupProcess()) {
            case "spxs":
                JgClassifySpxs classifySpxs = classifySpxsMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                jgRiskLevel.setCompanyTypeOne(classifySpxs == null ? "" : classifySpxs.getName());
                break;
            case "cyfw":
                JgClassifyCyfw classifyCyfw = classifyCyfwMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                jgRiskLevel.setCompanyTypeOne(classifyCyfw == null ? "" : classifyCyfw.getName());
                break;
            case "spsc":
                Map<String, Object> classifysc = classifySpscCompMapper.selectByCompanyId(jgRiskLevel.getCompanyId(), processCode.getId(), "1", "0");
                jgRiskLevel.setCompanyTypeOne(classifysc == null ? "" : classifysc.get("NAME").toString());
                break;
            case "tssc":
                Map<String, Object> classifyts = classifySpscCompMapper.selectByCompanyId(jgRiskLevel.getCompanyId(), processCode.getId(), "1", "1");
                jgRiskLevel.setCompanyTypeOne(classifyts == null ? "" : classifyts.get("NAME").toString());
                break;
        }
        List<JgCreditCustomScore> creditCustomScoreList = creditCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
        List<JgDynamicCustomScore> dynamicCustomScoreList = dynamicCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
        List<JgStaticCustomScore> staticCustomScoreList = staticCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
        jgRiskLevel.setCreditCustomScoreList(creditCustomScoreList);
        jgRiskLevel.setDynamicCustomScoreList(dynamicCustomScoreList);
        jgRiskLevel.setStaticCustomScoreList(staticCustomScoreList);

        List<JgRiskGradeScore> riskGradeScoreList = gradeScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
        jgRiskLevel.setRiskGradeScoreList(riskGradeScoreList);

        List<JgRiskLevelDynamic> riskLevelDynamicList = riskLevelDynamicMapper.selectByRiskLevelId(jgRiskLevel.getId());
        jgRiskLevel.setRiskLevelDynamicList(riskLevelDynamicList);

        Date riskTime = jgRiskLevel.getExamineTime();
        if (riskTime != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String examineTimeStr = simpleDateFormat.format(riskTime);
            jgRiskLevel.setExamineTimeStr(examineTimeStr);
        }
        return jgRiskLevel;

    }

    public JgRiskLevel getNoCheckRiskLevelInfo(Long companyId, Long riskLevelId) {
        //如果有之前未保存的 直接利用
        JgRiskLevel jgRiskLevel = null;
        if (riskLevelId == null) {
            jgRiskLevel = riskLevelMapper.selectByCompanyId(companyId, DateUtil.year(new Date()) + "", "2");
        } else {
            jgRiskLevel = riskLevelMapper.selectById(riskLevelId);
            companyId = jgRiskLevel.getCompanyId();
        }
        TcCompany company = companyMapper.selectById(companyId);

        //选择食用人群
        List<SysDictData> dictDataList = sysDictDataMapper.selectByDictTypeCode("risk_level_consumer");
        List<Map<String, Object>> consumerGroupList = new ArrayList<>();
        for (SysDictData sysDictData : dictDataList) {
            Map<String, Object> consumerGroup = new HashMap<>();
            consumerGroup.put("text", sysDictData.getDictLabel());
            consumerGroup.put("value", sysDictData.getDictValue());
            consumerGroupList.add(consumerGroup);
        }

        if (jgRiskLevel == null) {
            jgRiskLevel = new JgRiskLevel();
        }
        jgRiskLevel.setCreditCode(company.getCreditCode());
        jgRiskLevel.setLicense(company.getLicense());
        jgRiskLevel.setCompanyTypeId(company.getCompanyTypeId());
        jgRiskLevel.setCompanyTypeTwoId(company.getCompanyTypeTwoId());
        jgRiskLevel.setAdjustLevel(0);
        jgRiskLevel.setCompanyId(companyId);
        jgRiskLevel.setCompanyName(company.getCompanyName());
        jgRiskLevel.setDynamicMinusScore(0D);
        jgRiskLevel.setDynamicLevelScore(0D);
        jgRiskLevel.setStaticScaleScore(0D);
        jgRiskLevel.setCreditScore(0D);
        jgRiskLevel.setStaticCheckScore(0D);
        jgRiskLevel.setDeleteFlag(2);
        jgRiskLevel.setAdjustReason("");
        jgRiskLevel.setCreateTime(new Date());
        jgRiskLevel.setCreatorId(UserHelper.getUserId());
        jgRiskLevel.setCreator(UserHelper.getUserInfo().getName());
        jgRiskLevel.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
        jgRiskLevel.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
        jgRiskLevel.setConsumerGroup(company.getConsumerGroup());
        jgRiskLevel.setPersonTotal(company.getPersonTotal());
        jgRiskLevel.setAnnualIncome(company.getAnnualIncome());
        jgRiskLevel.setIsRenzheng(company.getIsRenzheng());
        jgRiskLevel.setIsZhuisu(company.getIsZhuisu());

        //获取企业今年的静态评分分值
        if (StringUtils.equals(company.getStaticScoreStatus(), "2")) {
            jgRiskLevel.setStaticSplbScore(0D);
            throw new RuntimeException("该企业今年还未进行静态评分!");
        }
        if (StringUtils.equals(company.getDynamicScoreStauts(), "2")) {
            jgRiskLevel.setStaticSplbScore(0D);
            throw new RuntimeException("该企业还未进行动态评分!");
        }
        JgStaticScoring staticScoring = staticScoringMapper.selectByCompanyId(companyId, null, "0");
        jgRiskLevel.setStaticScore(staticScoring.getScoreTotal());//静态总分初始情况等于静态检查的分值
        jgRiskLevel.setStaticSplbScore(staticScoring.getScoreTotal() == null ? 0D : staticScoring.getScoreTotal());
        jgRiskLevel.setStaticId(staticScoring.getId());
        jgRiskLevel.setSamplingScore(company.getSamplingScore() == null ? 0D : company.getSamplingScore());
        jgRiskLevel.setAppointmentScore(company.getAppointmentScore() == null ? 0D : company.getAppointmentScore());


        //计算动态评分   动态分数是上一年几次日常检查的得分和上一年的动态评分分数的平均分保留开两个小数
        QueryWrapper<JgDailyCheck> dailyCheckEntityQueryWrapper = new QueryWrapper<>();
        dailyCheckEntityQueryWrapper.eq("delete_flag", 0);
        dailyCheckEntityQueryWrapper.eq("company_id", companyId);
        dailyCheckEntityQueryWrapper.eq("CHECK_STAT", "1");
        dailyCheckEntityQueryWrapper.in("TYPE", "1", "2");
        dailyCheckEntityQueryWrapper.eq("check_year", DateUtil.year(new Date()) - 1);
        List<JgDailyCheck> dailyCheckEntityList = jgDailyCheckMapper.selectList(dailyCheckEntityQueryWrapper);
        BigDecimal dynamicTotalScore = new BigDecimal(0);
        Long currenYerRiskRestCount = riskLevelResetInfoMapper.selectCount(new QueryWrapper<JgRiskLevelResetInfo>().eq("DELETE_FLAG", "0")
                .eq("date_format(create_time,'%Y')", DateUtil.year(new Date()))
        );

        int checkTotal = 1;
        //如果上一年没有日常检查信息说明新入网 或者 今年有重新评级记录 这两个情况取距离评级时间最近的那条动态评分
        if ((dailyCheckEntityList.isEmpty() || currenYerRiskRestCount > 0) && company.getDynamicScoreId() != null) {
            JgDynamicScoring lastYearDynamicScoring = dynamicScoringMapper.selectById(company.getDynamicScoreId());
            dynamicTotalScore = dynamicTotalScore.add(new BigDecimal(lastYearDynamicScoring.getScoreTotal().toString()));
            jgRiskLevel.setDynamicId(lastYearDynamicScoring.getId());
        } else {
            for (JgDailyCheck jgDailyCheckEntity : dailyCheckEntityList) {
                //查询本次检查的得分
                BigDecimal totalScore = jgDailyContentMapper.selectTotalByDailyCheckId(jgDailyCheckEntity.getId());
                dynamicTotalScore = dynamicTotalScore.add(totalScore == null ? new BigDecimal(0) : totalScore);
            }
            checkTotal = dailyCheckEntityList.size();
        }


        if (checkTotal == 0) {
            checkTotal = 1;
        }
        ///取平均数
        dynamicTotalScore = dynamicTotalScore.divide(new BigDecimal(checkTotal), 2, BigDecimal.ROUND_HALF_UP);
        jgRiskLevel.setDynamicCheckScore(dynamicTotalScore.doubleValue());
        //如果没有检查过，默认检查人在进入页面的时候是当前登陆人
        // fixbug 检查人员提交审核申请 此处将 检查人员赋值给 审核人 字段？
//        jgRiskLevel.setExaminePersonnel(jgRiskLevel.getExaminePersonnel() == null ? UserHelper.getUserInfo().getName() : jgRiskLevel.getExaminePersonnel());
//        jgRiskLevel.setExaminePersonnelId(jgRiskLevel.getExaminePersonnelId() == null ? UserHelper.getUserId() : jgRiskLevel.getExaminePersonnelId());
        jgRiskLevel.setAdjustLevel(jgRiskLevel.getAdjustLevel() == null ? 0 : jgRiskLevel.getAdjustLevel());
        jgRiskLevel.setExamineResult(jgRiskLevel.getExamineResult() == null ? "2" : jgRiskLevel.getExamineResult());
        jgRiskLevel.setContactInformation(company.getContactPhone());
        jgRiskLevel.setCompanyAddress(company.getAddress());
        jgRiskLevel.setContacts(company.getContact());
        jgRiskLevel.setSupProcess(company.getSupProcess());
        jgRiskLevel.setConsumerGroupList(consumerGroupList);
        jgRiskLevel.setIsGongpi(jgRiskLevel.getIsGongpi() == null ? company.getIsGongpi() : jgRiskLevel.getIsGongpi());
        jgRiskLevel.setIsXiaoyuan(jgRiskLevel.getIsXiaoyuan() == null ? company.getIsXiaoyuan() : jgRiskLevel.getIsXiaoyuan());
        //获取上一年风险等级
        Calendar calendar = Calendar.getInstance();
        int lastYear = calendar.get(Calendar.YEAR);
        QueryWrapper<JgRiskLevel> riskLevelEntity = new QueryWrapper();
        riskLevelEntity.eq("COMPANY_ID", companyId);
        riskLevelEntity.eq("RISK_YEAR", (lastYear - 1) + "");
        List<JgRiskLevel> lastYearRiskLevelEntityList = riskLevelMapper.selectList(riskLevelEntity);
        if (lastYearRiskLevelEntityList.size() > 0) {
            jgRiskLevel.setLastYearLevel(lastYearRiskLevelEntityList.get(0).getRiskLevel());
        }
        //获取企业的一级业态信息
        JgProcessCode processCode = jgProcessCodeMapper.selectByCode(company.getSupProcess());
        jgRiskLevel.setSupProcessName(processCode.getName());
        switch (company.getSupProcess()) {
            case "spxs":
                JgClassifySpxs classifySpxs = classifySpxsMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                jgRiskLevel.setCompanyTypeOne(classifySpxs == null ? "" : classifySpxs.getName());
                break;
            case "cyfw":
                JgClassifyCyfw classifyCyfw = classifyCyfwMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                jgRiskLevel.setCompanyTypeOne(classifyCyfw == null ? "" : classifyCyfw.getName());
                break;
            case "spsc":
                Map<String, Object> classifysc = classifySpscCompMapper.selectByCompanyId(companyId, processCode.getId(), "1", "0");
                jgRiskLevel.setCompanyTypeOne(classifysc == null ? "" : classifysc.get("NAME").toString());
                break;
            case "tssc":
                Map<String, Object> classifyts = classifySpscCompMapper.selectByCompanyId(companyId, processCode.getId(), "1", "1");
                jgRiskLevel.setCompanyTypeOne(classifyts == null ? "" : classifyts.get("NAME").toString());
                break;
        }


        if (jgRiskLevel.getId() == null) {
            //生产企业获取各种自定义评分信息,刚进入新增
            List<JgCreditCustomProject> creditCustomProjectList = creditCustomProjectMapper.selectEntityList();
            List<JgCreditCustomScore> creditCustomScoreList = new ArrayList<>();
            for (JgCreditCustomProject jgCreditCustomProject : creditCustomProjectList) {
                JgCreditCustomScore creditCustomScore = new JgCreditCustomScore();
                creditCustomScore.setProjectId(jgCreditCustomProject.getId());
                creditCustomScore.setScore(0D);
                BeanUtil.copyProperties(jgCreditCustomProject, creditCustomScore, "id");
                creditCustomScoreList.add(creditCustomScore);
            }
            jgRiskLevel.setCreditCustomScoreList(creditCustomScoreList);
            //动态
            List<JgDynamicCustomProject> dynamicCustomProjectList = dynamicCustomProjectMapper.selectEntityList();
            List<JgDynamicCustomScore> dynamicCustomScoreList = new ArrayList<>();
            for (JgDynamicCustomProject jgDynamicCustomProject : dynamicCustomProjectList) {
                JgDynamicCustomScore dynamicCustomScore = new JgDynamicCustomScore();
                dynamicCustomScore.setProjectId(jgDynamicCustomProject.getId());
                dynamicCustomScore.setScore(0D);
                BeanUtil.copyProperties(jgDynamicCustomProject, dynamicCustomScore, "id");
                dynamicCustomScoreList.add(dynamicCustomScore);
            }
            jgRiskLevel.setDynamicCustomScoreList(dynamicCustomScoreList);
            //静态
            List<JgStaticCustomProject> staticCustomProjectList = staticCustomProjectMapper.selectEntityList();
            List<JgStaticCustomScore> staticCustomScoreList = new ArrayList<>();
            for (JgStaticCustomProject staticCustomProject : staticCustomProjectList) {
                JgStaticCustomScore staticCustomScore = new JgStaticCustomScore();
                BeanUtil.copyProperties(staticCustomProject, staticCustomScore, "id");
                staticCustomScore.setProjectId(staticCustomProject.getId());
                staticCustomScore.setScore(0D);
                staticCustomScoreList.add(staticCustomScore);
            }
            jgRiskLevel.setStaticCustomScoreList(staticCustomScoreList);
        } else {
            List<JgCreditCustomScore> creditCustomScoreList = creditCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
            List<JgDynamicCustomScore> dynamicCustomScoreList = dynamicCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
            List<JgStaticCustomScore> staticCustomScoreList = staticCustomScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
            jgRiskLevel.setCreditCustomScoreList(creditCustomScoreList);
            jgRiskLevel.setDynamicCustomScoreList(dynamicCustomScoreList);
            jgRiskLevel.setStaticCustomScoreList(staticCustomScoreList);
        }


        //其他自定义评分
        if (jgRiskLevel.getId() == null) {
            //说明没创建过评级
            List<JgRiskGrade> riskGradeList = gradeMapper.selectBySupProcessAndRegular(company.getSupProcess(), "0");
            List<JgRiskGradeScore> riskGradeScoreList = new ArrayList<>();
            for (JgRiskGrade jgRiskGrade : riskGradeList) {
                JgRiskGradeScore riskGradeScore = new JgRiskGradeScore();
                BeanUtil.copyProperties(jgRiskGrade, riskGradeScore, "id", "riskLevelId", "score", "gradeScore");
                riskGradeScore.setScore(0D);
                riskGradeScore.setGradeScore(0D);
                riskGradeScore.setDeleteFlag(0);
                riskGradeScore.setCreator(UserHelper.getUserInfo().getName());
                riskGradeScore.setCreateTime(new Date());
                riskGradeScore.setCreatorId(UserHelper.getUserId());
                riskGradeScoreList.add(riskGradeScore);
            }
            jgRiskLevel.setRiskGradeScoreList(riskGradeScoreList);
        } else {
            //说明已经进行过评级，或者临时保存过
            List<JgRiskGradeScore> riskGradeScoreList = gradeScoreMapper.selectByRiskLevelId(jgRiskLevel.getId());
            jgRiskLevel.setRiskGradeScoreList(riskGradeScoreList);
        }

        if (jgRiskLevel.getId() == null) {
            //说明没创建过评级
            List<JgRiskDynamicTemplate> riskDynamicTemplates = riskDynamicTemplateMapper.selectBySupProcess(company.getSupProcess());
            List<JgRiskLevelDynamic> riskLevelDynamicList = new ArrayList<>();
            for (JgRiskDynamicTemplate riskDynamicTemplate : riskDynamicTemplates) {
                JgRiskLevelDynamic riskLevelDynamic = new JgRiskLevelDynamic();
                BeanUtil.copyProperties(riskDynamicTemplate, riskLevelDynamic, "id", "riskLevelId", "selection");
                riskLevelDynamic.setRiskLevelId(jgRiskLevel.getId());
                riskLevelDynamic.setScore(riskDynamicTemplate.getScore());
                riskLevelDynamic.setSelection("0");
                riskLevelDynamic.setCreateTime(new Date());
                riskLevelDynamic.setDeleteFlag(0);
                riskLevelDynamic.setTemplateId(riskDynamicTemplate.getId());
                riskLevelDynamicList.add(riskLevelDynamic);
            }
            jgRiskLevel.setRiskLevelDynamicList(riskLevelDynamicList);
        } else {
            List<JgRiskLevelDynamic> riskLevelDynamicList = riskLevelDynamicMapper.selectByRiskLevelId(jgRiskLevel.getId());
            jgRiskLevel.setRiskLevelDynamicList(riskLevelDynamicList);
        }
        Date riskTime = jgRiskLevel.getExamineTime();
        if (riskTime != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String examineTimeStr = simpleDateFormat.format(riskTime);
            jgRiskLevel.setExamineTimeStr(examineTimeStr);
        }
        return jgRiskLevel;

    }

    /**
     * 保存评级信息
     *
     * @param temporarily 是否临时 1-临时;0-非临时
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgRiskLevel saveRiskLevelInfo(JgRiskLevel jgRiskLevel, String temporarily, TcCompany tcCompany, boolean companyLevelStatus) {
        log.info("企业等级评定保存信息:{}", jgRiskLevel);
        //总分数
        Double totalScore = 0.0;
        //先通过分值计算出等级，然后在判断动态调整之后再修改分级 最后再判断特殊的业态进行调整等级
        //根据规则判断经营企业中的某些特定类型企业
        synchronized ((tcCompany.getId() + "").intern()) {
            jgRiskLevel.setRiskYear(DateUtil.format(new Date(), "yyyy"));
            jgRiskLevel.setRiskTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            jgRiskLevel.setDeleteFlag(0);
            if ("0".equals(temporarily)) {
                jgRiskLevel.setExamineResult("2");
            }
            //计算总分数
            totalScore = calculationScore(jgRiskLevel);
            //获取风险等级
            String riskLevel = getRiskLevel(jgRiskLevel, tcCompany, companyLevelStatus, totalScore);
            jgRiskLevel.setRiskLevel(riskLevel);
            //保存数据来源
            jgRiskLevel.setSourceType(SOURCE_TYPE);
            if (jgRiskLevel.getId() == null) {
                riskLevelMapper.insert(jgRiskLevel);
            } else {
                riskLevelMapper.updateById(jgRiskLevel);
            }


            TcCompany company = companyMapper.selectById(tcCompany.getId());
            company.setRiskLevelId(jgRiskLevel.getId());
            companyMapper.updateById(company);
            //获取等级
//        String riskBusiness = map.get(tcCompany.getSupProcess()).findRiskBusiness(tcCompany, totalScore);


            //动态调整分数保存
            List<JgRiskLevelDynamic> riskLevelDynamicList = jgRiskLevel.getRiskLevelDynamicList();
            for (JgRiskLevelDynamic riskLevelDynamic : riskLevelDynamicList) {
                riskLevelDynamic.setRiskLevelId(jgRiskLevel.getId());
                if (riskLevelDynamic.getId() != null) {
                    riskLevelDynamicMapper.updateById(riskLevelDynamic);
                } else {
                    riskLevelDynamicMapper.insert(riskLevelDynamic);
                }
            }

            //自定义分数
            List<JgRiskGradeScore> riskGradeScoreList = jgRiskLevel.getRiskGradeScoreList();
            for (JgRiskGradeScore riskGradeScore : riskGradeScoreList) {
                riskGradeScore.setRiskLevelId(jgRiskLevel.getId());
                //JgRiskGrade grade = gradeMapper.selectBySupProcessAndRegularAndName(riskGradeScore.getSupProcess(), riskGradeScore.getIsRegular(), riskGradeScore.getGradeName());
                // if (riskGradeScore.getScore() > grade.getGradeValue()) {
                //     riskGradeScore.setGradeScore(grade.getGradeValue());
                // } else {
                //     riskGradeScore.setGradeScore(riskGradeScore.getScore());
                // }
                //原来按照比例计算的方法
                //riskGradeScore.setGradeScore(DoubleUtil.mul(riskGradeScore.getScore(), riskGradeScore.getGradeValue() / 100));
                riskGradeScore.setGradeScore(riskGradeScore.getScore());
                //加上总分
                totalScore = DoubleUtil.sum(totalScore, riskGradeScore.getScore());
                if (riskGradeScore.getId() != null) {
                    gradeScoreMapper.updateById(riskGradeScore);
                } else {
                    gradeScoreMapper.insert(riskGradeScore);
                }
            }
            return getRiskLevelInfo(jgRiskLevel.getId());
        }
    }

    public String getRiskLevel(JgRiskLevel jgRiskLevel, TcCompany tcCompany, Boolean companyLevelStatus, Double totalScore) {
        List<JgRiskLevelDynamic> riskLevelDynamicList = jgRiskLevel.getRiskLevelDynamicList();
        //调为D等级
        boolean selectedD = false;
        //上调等级
        boolean selectedUp = false;
        //下调等级
        boolean selectedDown = false;
        for (JgRiskLevelDynamic riskLevelDynamic : riskLevelDynamicList) {
            //动态调整等级
            switch (riskLevelDynamic.getType()) {
                case "1":
                    if (StringUtils.equals(riskLevelDynamic.getSelection(), "1")) {
                        //选择的调高等级
                        selectedUp = true;
                    }
                    continue;
                case "2":
                    if (StringUtils.equals(riskLevelDynamic.getSelection(), "1")) {
                        //选择的调低等级
                        selectedDown = true;
                    }
                    continue;
                case "3":
                    if (StringUtils.equals(riskLevelDynamic.getSelection(), "1")) {
                        //选择的是直接上调D等级
                        selectedD = true;
                    }
                    continue;
                case "4":
                    if (StringUtils.equals(riskLevelDynamic.getSelection(), "1")) {
                        //选择的是核减分数
                        totalScore = totalScore - ObjectUtil.defaultIfNull(riskLevelDynamic.getScore(), 0D);
                    }
                    continue;
            }
        }
        //按统一社会代码，查询列严信息
        Map<String, Object> lieYanByCreditCode = jgDsjYzwfsxmdMapper.getLieYanByCreditCode(tcCompany.getCreditCode());
        //通过分数设定等级
        String riskLevel = checkRiskLevelByScore(totalScore, 2);
        String risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
        jgRiskLevel.setRiskLevel(risk);
        boolean result = checkAquaticProduct(tcCompany);
        tcCompany.setIsXiaoyuan(jgRiskLevel.getIsXiaoyuan());

        //spxs:食品销售环节
        if (StringUtils.equals(tcCompany.getSupProcess(), PROCESS_SP)) {
            //一、校园及其周边100米范围内食品经营者、食用农产品（食品）批发市场评级时不管分数,并且被列入失信
            //1.食品销售者：校园及其周边100米范围内食品经营者，强制定级为D级，风险分值为实际分值，风险等级强制为D级且不可以调高或调低风险等级(文档序号：3) 。
            //2:食品销售者：按照《市场监督管理严重违法失信名单管理办法》，因实施食品安全领域违法行为被列入严重违法失信名单的;强制定级为D级。 (文档序号：5)
            //3:食用农产品销售者:校园及其周边100米范围内食品经营者:强制定级为D级。(文档序号：9)
            //4：食用农产品销售者：按照《市场监督管理严重违法失信名单管理办法》，因实施食品安全领域违法行为被列入严重违法失信名单的;强制定级为D级。（文档序号：10）
            //5:食品销售环节:食用农产品（食品）批发市场强制定级为D级。（文档序号：12）
            // 6：:集中交易市场开办者:校园及其周边100米范围内食品经营者(文档序号：15)
            // 7：按照《市场监督管理严重违法失信名单管理办法》，因实施食品安全领域违法行为被列入严重违法失信名单的;强制定级为D级。(文档序号：16）
            //8:食品(食用农产品)贮存服务提供者 按照《市场监督管理严重违法失信名单管理办法》，因实施食品安全领域违法行为被列入严重违法失信名单的;强制定级为D级。(文档序号：20)
            //8:食品销售连锁企业总部，因实施食品安全领域违法行为被列入严重违法失信名单的;强制定级为D级。(文档序号：21)
            if ("1".equals(jgRiskLevel.getIsXiaoyuan()) || lieYanByCreditCode != null) {
                //使用页面提交的数据进行判断，因为此时这个信息还未保存到企业中
                //锁死为D级
                jgRiskLevel.setRiskLevel("D");
            }
            //二、按其他规则验证等级
            //1.食品销售者:食品销售者且经营品种包含畜禽水产品（许可系统对接），最低级别为B级 （文档序号：2）
            else if (tcCompany.getCompanyTypeId() == 2L && result) {
                //获取等级
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //2：食品销售者:食品销售者且仅销售预包装食品,不在校园及其周边100米范围内食品经营者。（文档序号：4）
            else if (tcCompany.getCompanyTypeId() == 2L && StringUtils.isNotEmpty(tcCompany.getIsYbz()) && StringUtils.equals(tcCompany.getIsYbz(), "1")) {
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            } else if (tcCompany.getCompanyTypeId() == 2L) {// 2025-1-9 新增代码 lu
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //3.食品销售者：食品销售者且经营项目中含“制售”字段的，不得低于B级：即当风险分值小于30分时，强制定级为B级及以上。（文档序号：6）
            //天津银石宜嘉商贸有限公司
            else if (tcCompany.getCompanyTypeId() == 2L && StringUtils.contains(tcCompany.getBusinessScope(), "制售")) {
                //获取分值
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }

            //4:食品销售者:食品销售者且经营项目包含特殊食品销售。(文档序号：7) 略
            //天津银石宜嘉商贸有限公司
            else if (tcCompany.getCompanyTypeId() == 2L && StringUtils.contains(tcCompany.getBusinessScope(), "特殊食品销售")) {
                //获取分值
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }


            //5:食用农产品销售者:食用农产品销售者且经营品种包含畜禽水产品，不得低于B级：即当风险分值小于30分时，强制定级为B级及以上.(文档序号：8)
            else if (tcCompany.getCompanyTypeId() == 5L && companyLevelStatus) {
                //获取分值
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }

            //6:食用农产品销售者,(文档序号：11) 走 else {}
//            else if (tcCompany.getCompanyTypeId() == 5L) {
//                //获取分值
//                String riskLevel = checkRiskLevelByScore(totalScore, 2);
//                String risk = calculationRiskLevel(riskLevel, selectedD, selectedUp, selectedDown, adjustLevel);
//                jgRiskLevel.setRiskLevel(risk);
//            }

            //食用农产品（食品）批发市场
            //7:食品销售连锁企业总部,食品销售连锁企业总部（新增）强制定级为D级 联锁企业总部(13)
            //8:集中交易市场开办者:集中交易市场开办者且是食用农产品（食品）批发市场强制定级为D级。(文档序号：14)
            else if (tcCompany.getCompanyTypeId() == 13L || (tcCompany.getCompanyTypeId() == 3L && "1".equals(tcCompany.getIsGongpi()))) {
                //锁死为D级
                jgRiskLevel.setRiskLevel("D");
            }

            //8:集中交易市场开办者:(文档序号：17)
            //9:网络食品交易(含网络餐饮服务)第三方平台提供者:(文档序号：18)
            else if ((tcCompany.getCompanyTypeId() == 3L && !"1".equals(tcCompany.getIsGongpi())) || tcCompany.getCompanyTypeId() == 4L) {
                //获取分值
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //10:食品(食用农产品)贮存服务提供者，最低级别为B级。 (文档序号：19)
            else if (tcCompany.getCompanyTypeId() == 6L && StringUtils.equals(tcCompany.getIsFrozenFoodStorage(), "1")) {
                //获取分值
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            } else {
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
        }
        //cyfw:餐饮服务
        else if (StringUtils.equals(tcCompany.getSupProcess(), PROCESS_CY)) {
            //一、校园及其周边100米范围内食品经营者、食用农产品（食品）批发市场评级时不管分数,并且被列入失信 (文档序号：28)
            //1.社会餐饮服务经营者:强制定级为D级后，不可以 进行调高或调低等级。
            boolean verifySchool = getVerifySchool(tcCompany);
            if (verifySchool || lieYanByCreditCode != null) {
                //锁死为D级
                jgRiskLevel.setRiskLevel("D");
            }
            //companyTypeId:2-社会餐饮服务经营者，最低级别为B级
            //companyTypeId:5-固定食品制售摊贩，设座小餐饮固定食品制售餐饭，最低级别为B级
            //companyTypeId:21-小餐饮，设座小餐饮固定食品制售餐饭，最低级别为B级
            else if (tcCompany.getCompanyTypeId() == 2L || (tcCompany.getCompanyTypeId() == 5L &&
                    "1".equals(tcCompany.getIsShezuo())) || (tcCompany.getCompanyTypeId() == 21L &&
                    "1".equals(jgRiskLevel.getIsShezuo()))) {
                //1:最低级别为:B
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //getCompanyTypeTwoId:13 其他食堂
            //getCompanyTypeTwoId:14 职工食堂
            //getCompanyTypeTwoId:32 托管服务机构食堂
            //getCompanyTypeTwoId:33 机关单位食堂
            //getCompanyTypeTwoId:34 监狱食堂
            //getCompanyTypeTwoId:35 月子会所食堂
            //getCompanyTypeTwoId:37 托育机构食堂
            else if ((tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 13) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 14) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 32) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 33) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 34) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 35) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 37)) {
                //1:最低级别为:B
                riskLevel = checkRiskLevelByScore(totalScore, 1);
                risk = calculationRiskLevel(riskLevel, B_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //companyTypeId:5-固定食品制售摊贩,isShezuo:0 不设座的固定食品制售摊贩
            //companyTypeId:22-餐车（亭）摊贩
            //companyTypeId:5-固定食品制售摊贩,0：不设座
            //companyTypeId:6-早餐车（亭）摊贩
            else if (StringUtils.equalsAny(tcCompany.getCompanyTypeId() + "",
                    "6", "22")
                    || (StringUtils.equals(tcCompany.getCompanyTypeId() + "", "5") &&
                    "0".equals(tcCompany.getIsShezuo()))) {
                //2:最低级别为:A
                riskLevel = checkRiskLevelByScore(totalScore, 2);
                risk = calculationRiskLevel(riskLevel, A_LEVEL, selectedD, selectedUp, selectedDown, jgRiskLevel.getAdjustLevel());
                jgRiskLevel.setRiskLevel(risk);
            }
            //2.中央厨房和集体用餐配送单位,强制定级为D级。  (文档序号：28)
            //- 3.单位食堂（学校食堂）学校食堂、托幼机构食堂、养老机构食堂、医疗机构食堂、建筑工地食堂、职工食堂、托育机构食堂、托幼机构食堂等.强制定级为D级。
            //- 4:餐饮服务连锁企业总部,餐饮服务连锁企业总部:强制定级为D级
            //- 7:养老机构食堂
            //8:学校（含托幼机构）食堂
            //9:医疗机构食堂
            //10:工地食堂
            //11:中央厨房
            //12:集体用餐配送单位
            //29:餐饮服务连锁企业总部
            //30:餐饮服务管理企业
            //21:不设座的小餐饮，强制D级
            //：4 单位食堂(学校食堂)定级为D级别
            //companyTypeId：4 单位食堂(学校食堂) 、getCompanyTypeTwoId：7 养老机构食堂
            //companyTypeId：4 单位食堂(学校食堂) 、getCompanyTypeTwoId：8 学校（含托幼机构）食堂
            //companyTypeId：4 单位食堂(学校食堂) 、getCompanyTypeTwoId：9 医疗机构食堂
            //companyTypeId：4 单位食堂(学校食堂) 、getCompanyTypeTwoId：10 工地食堂
            else if (tcCompany.getCompanyTypeId() == 3L ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 7) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 8) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 9) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 10) ||
                    (tcCompany.getCompanyTypeId() == 4L && tcCompany.getCompanyTypeTwoId() == 38) ||
                    tcCompany.getCompanyTypeId() == 11 ||
                    tcCompany.getCompanyTypeId() == 12 ||
                    tcCompany.getCompanyTypeId() == 29 ||
                    tcCompany.getCompanyTypeId() == 30 ||
                    (tcCompany.getCompanyTypeId() == 21 && "0".equals(jgRiskLevel.getIsShezuo()))) {

                //锁死为D级
                jgRiskLevel.setRiskLevel("D");
            }
        }
        //cyfw:餐饮服务环节
        return jgRiskLevel.getRiskLevel();

    }


    /**
     * 按分值验证评级
     *
     * @param totalScore 分数
     * @return
     */
    public String checkRiskLevelByScore(Double totalScore, Integer type) {

        if (type == 1) {
            if (totalScore <= 45) {
                return "B";
            } else if (totalScore > 45 && totalScore <= 60) {
                return "C";
            } else if (totalScore > 60) {
                return "D";
            }
        } else {
            //通过计算的分数进行判断风险等级
            if (totalScore <= 30) {
                return "A";
            } else if (totalScore > 30 && totalScore <= 45) {
                return "B";
            } else if (totalScore > 45 && totalScore <= 60) {
                return "C";
            } else if (totalScore > 60) {
                return "D";
            }
        }

        return null;
    }

    /**
     * 计算调试等级
     *
     * @param risk         最低评级至
     * @param selectedD    调为D等级
     * @param selectedUp   上调等级
     * @param selectedDown 下调等级
     * @param adjustLevel  升级指数
     * @return
     */
    public String calculationRiskLevel(String risk, String minLevel, boolean selectedD, boolean selectedUp, boolean selectedDown, Integer adjustLevel) {
        //先通过分值计算出等级，然后在判断动态调整之后再修改分级 最后再判断特殊的业态进行调整等级
        List<String> levelList = Lists.newArrayList("A", "B", "C", "D");
        if (selectedD) {
            return "D";
        } else {
            //当前等级在levelList中的第几个
            int levelIndex = levelList.indexOf(risk);
            if (levelIndex < 0) {
                //没有数值
                levelIndex = 0;
            }
            //根据选择的调高和调低等级的选择来调整等级
            if (selectedUp) {
                //调高等级
                levelIndex = levelIndex + (adjustLevel == null ? 0 : adjustLevel);
                if (levelIndex > 3) {
                    levelIndex = 3;
                }
                return levelList.get(levelIndex);
            }
            if (selectedDown) {
                //调低等级
                levelIndex = levelIndex - (adjustLevel == null ? 0 : adjustLevel);
                if (levelIndex < 0) {
                    return minLevel;
                }
                return levelList.get(levelIndex);
            }
        }

        return risk;
    }

    public boolean checkAquaticProduct(TcCompany company) {
        /**
         * 0 猪肉
         * 1 牛肉
         * 2 禽类及其产品
         * 3 水产品
         */
        if ((company.getCompanyTypeId() == 3L || company.getCompanyTypeId() == 5L) && StringUtils.isNotEmpty(company.getBusinessScope())) {
            if (company.getBusinessScope().contains("猪肉") || company.getBusinessScope().contains("牛羊肉") || company.getBusinessScope().contains("禽类及其产品") || company.getBusinessScope().contains("水产品")) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean getVerifySchool(TcCompany company) {
        //companyTypeId:2 社会餐饮服务经营、companyTypeTwoId：23：餐饮服务连锁企业总部(不强制定级D)
        //companyTypeId:3 中央厨房和集体用餐配送单位。 companyTypeTwoId：11 中央厨房(不强制定级D)
        //companyTypeId：29 餐饮服务连锁企业总部、companyTypeId：3 0餐饮服务管理企业(不强制定级D)
        if ((company.getCompanyTypeId().equals("2") && !company.getCompanyTypeTwoId().equals("23")) && "1".equals(company.getIsXiaoyuan())) {
            return true;
        } else if ((!company.getCompanyTypeId().equals("3") || !company.getCompanyTypeTwoId().equals("11")) && "1".equals(company.getIsXiaoyuan())) {
            return true;
        } else if ((!company.getCompanyTypeId().equals("29") || !company.getCompanyTypeId().equals("30")) && "1".equals(company.getIsXiaoyuan())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 计算分数
     *
     * @param jgRiskLevel
     * @return
     */
    public Double calculationScore(JgRiskLevel jgRiskLevel) {
        Double totalScore = 0.0;
        //静态、动态、信用自定义分值计算
        Double dynamicCustom = 0D;
        Double staticCustom = 0D;
        Double creditCustom = 0D;
        //生产企业
        for (JgDynamicCustomScore dynamicCustomScore : jgRiskLevel.getDynamicCustomScoreList()) {
            dynamicCustomScore.setRiskLevelId(jgRiskLevel.getId());
            // if (dynamicCustomScore.getScore() > dynamicCustomScore.getGradeValue()) {
            //    dynamicCustomScore.setScore(dynamicCustomScore.getGradeValue());
            // }
            dynamicCustom = DoubleUtil.sum(dynamicCustom, dynamicCustomScore.getScore());
            if (dynamicCustomScore.getId() != null) {
                dynamicCustomScoreMapper.updateById(dynamicCustomScore);
            } else {
                dynamicCustomScoreMapper.insert(dynamicCustomScore);
            }
        }

        //生产企业
        for (JgStaticCustomScore staticCustomScore : jgRiskLevel.getStaticCustomScoreList()) {
            staticCustomScore.setRiskLevelId(jgRiskLevel.getId());
            // System.out.println("staticCustomScore.getScore():"+staticCustomScore.getScore());
            // System.out.println("staticCustomScore.getGradeValue():"+staticCustomScore.getGradeValue());
            //if (staticCustomScore.getScore() > staticCustomScore.getGradeValue()) {
            //    staticCustomScore.setScore(staticCustomScore.getGradeValue());
            // }
            staticCustom = DoubleUtil.sum(staticCustom, staticCustomScore.getScore());
            if (staticCustomScore.getId() != null) {
                staticCustomScoreMapper.updateById(staticCustomScore);
            } else {
                staticCustomScoreMapper.insert(staticCustomScore);
            }
        }

        //生产企业
        for (JgCreditCustomScore creditCustomScore : jgRiskLevel.getCreditCustomScoreList()) {
            creditCustomScore.setRiskLevelId(jgRiskLevel.getId());
            if (creditCustomScore.getScore() > creditCustomScore.getGradeValue()) {
                creditCustomScore.setScore(creditCustomScore.getGradeValue());
            }
            creditCustom = DoubleUtil.sum(creditCustom, creditCustomScore.getScore());
            if (creditCustomScore.getId() != null) {
                creditCustomScoreMapper.updateById(creditCustomScore);
            } else {
                creditCustomScoreMapper.insert(creditCustomScore);
            }
        }


        //静态、动态、信用总分值计算
        List<JgRiskGrade> riskGradeList = gradeMapper.selectBySupProcessAndRegular(jgRiskLevel.getSupProcess(), "1");
        for (JgRiskGrade riskGrade : riskGradeList) {
            if ("静态评分".equals(riskGrade.getGradeName())) {
                //按照最大值的算法
                double staticScore = DoubleUtil.sum(jgRiskLevel.getStaticCheckScore() == null ? 0 : jgRiskLevel.getStaticCheckScore(), jgRiskLevel.getStaticScaleScore() == null ? 0 : jgRiskLevel.getStaticScaleScore());
                staticScore = DoubleUtil.sum(staticScore, jgRiskLevel.getStaticSplbScore() == null ? 0 : jgRiskLevel.getStaticSplbScore());
                staticScore = DoubleUtil.sum(staticScore, staticCustom);
                if (staticScore > riskGrade.getGradeValue()) {
                    jgRiskLevel.setStaticScore(riskGrade.getGradeValue());
                } else {
                    jgRiskLevel.setStaticScore(staticScore);
                }
                // 之前按照比例的算法
                //double staticGradeScore = DoubleUtil.mul(jgRiskLevel.getStaticScore(), riskGrade.getGradeValue() / 100);
                totalScore = DoubleUtil.sum(totalScore, jgRiskLevel.getStaticScore());
            }
            if ("动态评分".equals(riskGrade.getGradeName())) {
                double dynamicCheckScore = jgRiskLevel.getDynamicCheckScore() == null ? 0.0 : jgRiskLevel.getDynamicCheckScore();
                jgRiskLevel.setDynamicScore(dynamicCheckScore);
                dynamicCheckScore = DoubleUtil.sum(dynamicCheckScore, jgRiskLevel.getSamplingScore() == null ? 0D : jgRiskLevel.getSamplingScore());
                dynamicCheckScore = DoubleUtil.sum(dynamicCheckScore, jgRiskLevel.getAppointmentScore() == null ? 0D : jgRiskLevel.getAppointmentScore());
                dynamicCheckScore = DoubleUtil.sum(dynamicCheckScore, dynamicCustom);
                if (dynamicCheckScore > riskGrade.getGradeValue()) {
                    jgRiskLevel.setDynamicCheckScore(riskGrade.getGradeValue());
                } else {
                    jgRiskLevel.setDynamicCheckScore(dynamicCheckScore);
                }
                // 之前按照比例的算法
                // double staticGradeScore = DoubleUtil.mul(jgRiskLevel.getDynamicCheckScore(), riskGrade.getGradeValue() / 100);
                totalScore = DoubleUtil.sum(totalScore, jgRiskLevel.getDynamicCheckScore());
            }
            if ("信用评分".equals(riskGrade.getGradeName())) {
                double creditScore = jgRiskLevel.getCreditScore();
                jgRiskLevel.setCreditBaseScore(creditScore);
                creditScore = DoubleUtil.sum(creditScore, creditCustom);
                if (jgRiskLevel.getCreditScore() > riskGrade.getGradeValue()) {
                    jgRiskLevel.setCreditScore(riskGrade.getGradeValue());
                } else {
                    jgRiskLevel.setCreditScore(creditScore);
                }
                //之前按照比例的算法
                //double staticGradeScore = DoubleUtil.mul(jgRiskLevel.getCreditScore(), riskGrade.getGradeValue() / 100);
                totalScore = DoubleUtil.sum(totalScore, jgRiskLevel.getCreditScore());
            }
        }
        //计算核减分值
        totalScore = DoubleUtil.sum(totalScore, jgRiskLevel.getDynamicMinusScore());
        return totalScore;
    }


    /**
     * 保存审核信息
     *
     * @param riskId         风险评分id
     * @param examineResult  评分结果
     * @param examineOpinion 评分意见
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRiskLevelExamine(Long riskId, String examineResult, String examineOpinion) {
        if (riskId == null) {
            throw new RuntimeException("风险评分主键信息为空!");
        }
        JgRiskLevel riskLevel = null;
        try {
            riskLevel = riskLevelMapper.selectById(riskId);
            riskLevel.setExamineResult(examineResult);
            riskLevel.setExamineOpinion(examineOpinion);
            riskLevel.setExamineTime(new Date());
            riskLevel.setExaminePersonnelId(UserHelper.getUserId());
            riskLevel.setExaminePersonnel(UserHelper.getUserInfo().getName());
            riskLevelMapper.updateById(riskLevel);
        } catch (Exception e) {
            log.error("保存风险等级审核信息失败", e);
            throw new RuntimeException("保存风险等级审核信息失败!");
        }
        if ("1".equals(examineResult)) {
            //如果审核通过，修改企业部分信息
            TcCompany company = null;
            try {
                company = companyMapper.selectById(riskLevel.getCompanyId());
                company.setIsShezuo(riskLevel.getIsShezuo());
                company.setConsumerGroup(riskLevel.getConsumerGroup());
                company.setPersonTotal(riskLevel.getPersonTotal());
                company.setAnnualIncome(riskLevel.getAnnualIncome());
                company.setIsRenzheng(riskLevel.getIsRenzheng());
                company.setIsZhuisu(riskLevel.getIsZhuisu());
                company.setRiskLevel(riskLevel.getRiskLevel());
                company.setRiskLevelDate(riskLevel.getRiskTime() == null ? DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") : riskLevel.getRiskTime());
                company.setIsGongpi(riskLevel.getIsGongpi());
                company.setIsXiaoyuan(riskLevel.getIsXiaoyuan());
                company.setInspectStartDate(new Date());
                company.setIsReRating(0);
                companyMapper.updateById(company);
            } catch (Exception e) {
                log.error("保存风险等级失败", e);
                throw new RuntimeException("保存风险等级失败!");
            }

            // 将动态检查数据同步至日常检查
            try {
                JgDynamicScoring dynamicScoring = dynamicScoringMapper.findJgDynamicScoringOverByCompanyId(riskLevel.getCompanyId());
                if (dynamicScoring != null) {
                    JgDailyCheck dailyCheck = new JgDailyCheck();
                    BeanUtil.copyProperties(dynamicScoring, dailyCheck, "id");

                    if (!"1".equals(dynamicScoring.getCopeResult()) && StringUtils.isEmpty(dynamicScoring.getResultTime())) {
                        //整改日期赋值,默认30天后 格式化为字符串
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        String format = LocalDate.now().plusDays(30).format(formatter);
                        dailyCheck.setRectificationTimeLimit(format);
                    }
                    //根据业态等内容查询一年检查次数 由于生产和特食的评级分离开了 这里不进行判断了(特食需要判断业态)
                    QueryWrapper<JgDailyCheckSet> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("RISK_LEVEL", company.getRiskLevel());
                    queryWrapper.eq("DELETE_FLAG", "0");
                    queryWrapper.eq("SUP_PROCESS", company.getSupProcess());
                    JgDailyCheckSet dailyCheckSet = null;
                    if (StringUtils.equalsAny(company.getSupProcess(), "tssc")) {
                        //需要匹配业态
                        List<JgClassifySpscComp> classifySpscComps = jgClassifySpscCompMapper.selectEntityByCompanyId(company.getId());
                        List<Long> classcifyId = classifySpscComps.stream().map(JgClassifySpscComp::getClassifySpsc1Id).collect(Collectors.toList());
                        queryWrapper.in("REGULATORY_FORMATS", classcifyId);
                        List<JgDailyCheckSet> dailyCheckSetList = jgDailyCheckSetMapper.selectList(queryWrapper);
                        //比较出frequency检查频次最大的数据
                        dailyCheckSet = dailyCheckSetList.stream().max(Comparator.comparing(JgDailyCheckSet::getFrequency)).get();
                    } else {
                        dailyCheckSet = jgDailyCheckSetMapper.selectOne(queryWrapper);
                    }
                    //根据频次和时间间隔计算出每次检查的时间段
                    Date startDate = DateUtil.parse((DateUtil.year(new Date()) - 1) + "-12-31", "yyyy-MM-dd");
                    List<Date> dateList = new ArrayList<>();
                    if (dailyCheckSet != null) {
                        for (int i = 0; i < dailyCheckSet.getFrequency(); i++) {
                            startDate = DateUtil.offsetMonth(startDate, Integer.valueOf(ObjectUtil.defaultIfNull((dailyCheckSet.getGapMonth()) + "", "0")));
                            dateList.add(startDate);
                        }
                    }

                    //根据检查时间判断是第几次检查
                    for (int i = 0; i < dateList.size(); i++) {
                        if (DateUtil.compare(dateList.get(i), new Date(), "yyyy-MM-dd") > 0) {
                            //当前时间比哪个时间段小，说明就在这次的检查次数中
                            dailyCheck.setCheckNum(Long.parseLong((i + 1) + ""));
                            break;
                        }
                    }
                    dailyCheck.setDelayCheck(0);
                    dailyCheck.setCheckResult(dynamicScoring.getCheckResults());//检查结果
                    dailyCheck.setProcessResults(dynamicScoring.getCopeResult());//处理结果//处理结果
                    dailyCheck.setRectificationTimeLimit(dynamicScoring.getResultTime());
                    dailyCheck.setCheckYear(Long.parseLong(dynamicScoring.getScoreYear()));
                    dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
                    dailyCheck.setCreateTime(new Date());
                    dailyCheck.setCheckStat("1");
                    dailyCheck.setIsUnplanned("0");
                    dailyCheck.setType("1");
                    dailyCheck.setDeleteFlag(0L);
                    dailyCheck.setAbnormalCause(dynamicScoring.getAbnormalReason());
                    dailyCheck.setCheckItemTableUrl(dynamicScoring.getKeyPointsTableUrl());
                    dailyCheck.setResultRecordUrl(dynamicScoring.getCheckRecordTableUrl());
                    dailyCheck.setCheckPerson1Id(dynamicScoring.getCheckPerson1Id() == null ? dynamicScoring.getScorePerson1Id() : dynamicScoring.getCheckPerson1Id());
                    dailyCheck.setCheckPerson2Id(dynamicScoring.getCheckPerson2Id() == null ? dynamicScoring.getScorePerson2Id() : dynamicScoring.getCheckPerson2Id());
                    dailyCheck.setCheckPerson1Name(dynamicScoring.getCheckPerson1Name() == null ? dynamicScoring.getScorePerson1Name() : dynamicScoring.getCheckPerson1Name());
                    dailyCheck.setCheckPerson2Name(dynamicScoring.getCheckPerson2Name() == null ? dynamicScoring.getScorePerson2Name() : dynamicScoring.getCheckPerson2Name());

                    QueryWrapper<JgDailyCheck> dailyCheckEntityQueryWrapper = new QueryWrapper();
                    dailyCheckEntityQueryWrapper.eq("delete_flag", "0");
                    dailyCheckEntityQueryWrapper.eq("check_year", DateUtil.year(new Date()));
                    dailyCheckEntityQueryWrapper.eq("type", "1");
                    dailyCheckEntityQueryWrapper.eq("is_unplanned", "0");
                    dailyCheckEntityQueryWrapper.eq("company_id", riskLevel.getCompanyId());
                    dailyCheckEntityQueryWrapper.eq("check_num", dailyCheck.getCheckNum());
                    List<JgDailyCheck> dailyCheckList = jgDailyCheckMapper.selectList(dailyCheckEntityQueryWrapper);

                    boolean inserStatus = false;

                    if (dailyCheckList.isEmpty()) {
                        //没检查过
                        inserStatus = true;
                        jgDailyCheckMapper.insert(dailyCheck);
                    } else {
                        AtomicBoolean flag = new AtomicBoolean(false);
                        AtomicLong id = new AtomicLong();
                        dailyCheckList.stream().forEach(dailyCheckEntity -> {
                            if (StringUtils.equals(dailyCheckEntity.getCheckStat(), "1")) {
                                flag.set(true);
                                id.set(dailyCheckEntity.getId());
                            }
                        });
                        if (!flag.get()) {
                            //没检查完成的
                            inserStatus = true;
                            dailyCheck.setId(id.get());
                            jgDailyCheckMapper.updateById(dailyCheck);
                            //删除之前的检查项目
                            List<JgDynamicStandard> oldDynamicStandardList = dynamicStandardMapper.selectList(new QueryWrapper<JgDynamicStandard>().eq("DYNAMIC_SCORING_ID", id.get()));
                            for (JgDynamicStandard jgDynamicStandardEntity : oldDynamicStandardList) {
                                jgDynamicStandardEntity.setDeleteFlag(1L);
                                dynamicStandardMapper.updateById(jgDynamicStandardEntity);
                                JgDynamicContent updateEntity = new JgDynamicContent();
                                updateEntity.setDeleteFlag(1L);
                                jgDynamicContentMapper.update(updateEntity, new QueryWrapper<JgDynamicContent>().eq("DYNAMIC_STANDARD_ID", id.get()));
                            }
                        }
                    }

                    if (inserStatus) {
                        List<JgDynamicStandard> dsList = dynamicStandardMapper.selectByDynamicCheckId(dynamicScoring.getId());
                        List<JgDynamicContent> dcAllList = dynamicContentMapper.selectByDynamicCheckId(dynamicScoring.getId());
                        Map<Long, JgDailyStandard> dailyStandardMap = new HashMap<>();
                        List<JgDailyStandard> dailyStandardInsertList = new ArrayList<>();
                        for (JgDynamicStandard ds : dsList) {
                            JgDailyStandard jds = new JgDailyStandard();
                            BeanUtil.copyProperties(ds, jds, "id", "supCategory");
                            jds.setDailyCheckId(dailyCheck.getId());
                            jds.setSupCategory("1");
//                        jgDailyStandardMapper.insert(jds);
                            dailyStandardInsertList.add(jds);
                            dailyStandardMap.put(ds.getId(), jds);
                        }
                        if (!dailyStandardInsertList.isEmpty()) {
                            jgDailyStandardMapper.batchInsert(dailyStandardInsertList);
                        }
                        List<JgDailyContent> dailyContentInsertList = new ArrayList<>();
                        for (JgDynamicStandard ds : dsList) {
                            JgDailyStandard jds = dailyStandardMap.get(ds.getId());
                            List<JgDynamicContent> dcList = dcAllList.stream().filter(dc -> Objects.equals(ds.getId(), dc.getDynamicStandardId())).collect(Collectors.toList());
                            //dynamicContentMapper.selectByStandardId(ds.getId());
                            for (JgDynamicContent dc : dcList) {
                                JgDailyContent jdc = new JgDailyContent();
                                BeanUtil.copyProperties(dc, jdc, "id");
                                jdc.setDailyStandardId(jds.getId());
//                            jgDailyContentMapper.insert(jdc);
                                //log.info("风险分级即将批量插入的值未=================",jdc.toString());
                                dailyContentInsertList.add(jdc);
                            }
                        }
                        if (!dailyContentInsertList.isEmpty()) {
                            jgDailyContentMapper.batchInsert(dailyContentInsertList);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("生成日常检查信息失败", e);
                throw new RuntimeException("生成日常检查信息失败!");
            }

            //保存企业初次入网信息,判断企业是否存在初次入网信息，如果不存在则新增如果存在则不用管
            try {
                QueryWrapper<JgCompanyInware> queryWrapper = new QueryWrapper();
                queryWrapper.eq("COMPANY_ID", riskLevel.getCompanyId());
                queryWrapper.eq("DELETE_FLAG", "0");
                List<JgCompanyInware> firstNetList = jgCompanyInwareMapper.selectList(queryWrapper);
                if (firstNetList.isEmpty()) {
                    JgCompanyInware firstNet = new JgCompanyInware();
                    firstNet.setDeleteFlag(0);
                    firstNet.setCreateTime(new Date());
                    firstNet.setInTime(new Date());
                    firstNet.setInYear(DateUtil.year(new Date()));
                    firstNet.setCompanyId(riskLevel.getCompanyId());
                    firstNet.setRiskLevelId(riskId);
                    jgCompanyInwareMapper.insert(firstNet);
                }
            } catch (Exception e) {
                log.error("保存出入入网信息失败", e);
                throw new RuntimeException("保存出入入网信息失败!");
            }

        }


    }

    /**
     * 通过检查的内容获取风险xinxi
     *
     * @param checkContentId
     * @return
     */
    public List<Map<String, Object>> getRiskTypeByCheckContent(Long checkContentId) {
        return riskCheckContentMapper.selectRiskTypeByCheckContent(checkContentId);
    }

    public TcCompany findCompanyById(Long companyId) {
        return companyMapper.selectById(companyId);
    }

    @DS("ads")
    public JgSpjyxk findAdsJgSpjyxkByLisenceNo(String license) {
        return jgSpjyxkMapper.selectByLicense(license);

    }

    @DS("ads")
    public JgSpzc findAdsJgSpzcByLisenceNo(String license) {
        return jgSpzcMapper.selectByLicense(license);
    }

    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表  JgDynamicScoring id
     * @return
     */
    public Map<String, Object> getRiskResultTable(Long checkId) {
        Map<String, Object> checkInfo = dynamicScoringMapper.selectMapById(checkId);
        List<JgDynamicContent> contentList = dynamicContentMapper.selectByDynamicCheckId(checkId);
        Integer contentNum = contentList.size();
        Integer importNum = 0; //重点项
        Integer importProblemNum = 0; //发现问题
        Integer commonlyNum = 0; //一般项
        Integer commonlyProblemNum = 0; //发现问题
        List<String> importNo = new ArrayList<>();//重点项序号
        List<String> importProblemNo = new ArrayList<>();//重点项序号
        List<String> commonlyNo = new ArrayList<>();//一般项序号
        List<String> commonlyProblemNo = new ArrayList<>();//一般项序号
        for (JgDynamicContent content : contentList) {
            //IMPORTENT_ITEM is '重要项：1一般项，2重要项
            //SELECTION is '选择项：1是、2否、3合理缺项
            if (StringUtils.equals(content.getImportentItem() + "", "1")) {
                commonlyNum = commonlyNum + 1;
                commonlyNo.add(Math.round(content.getStandardNum()) + "." + Math.round(content.getSerialNum()));
                if (StringUtils.equals(content.getSelection(), "2")) {
                    commonlyProblemNo.add(Math.round(content.getStandardNum()) + "." + Math.round(content.getSerialNum()));
                }
                if (StringUtils.equals(content.getSelection(), "2")) {
                    commonlyProblemNum = commonlyProblemNum + 1;
                }

            } else if (StringUtils.equals(content.getImportentItem(), "2")) {
                importNum = importNum + 1;
                //如果内容文字不匹配则查询序号字段
                importNo.add(Math.round(content.getStandardNum()) + "." + Math.round(content.getSerialNum()));
                if (StringUtils.equals(content.getSelection(), "2")) {
                    importProblemNo.add(Math.round(content.getStandardNum()) + "." + Math.round(content.getSerialNum()));
                }
                if (StringUtils.equals(content.getSelection(), "2")) {
                    importProblemNum = importProblemNum + 1;
                }
            }
        }
        checkInfo.put("contentNum", contentNum);
        checkInfo.put("importNum", importNum);
        checkInfo.put("importProblemNum", importProblemNum);
        checkInfo.put("commonlyNum", commonlyNum);
        checkInfo.put("commonlyProblemNum", commonlyProblemNum);
        checkInfo.put("importNo", String.join(" ; ", importNo));
        checkInfo.put("importProblemNo", String.join(" ; ", importProblemNo));
        checkInfo.put("commonlyNo", String.join(" ; ", commonlyNo));
        checkInfo.put("commonlyProblemNo", String.join(" ; ", commonlyProblemNo));
        //生成单子编号
        if (ObjectUtil.isNotEmpty(checkInfo.get("SUP_PROCESS")) && (StringUtils.equalsAny(checkInfo.get("SUP_PROCESS").toString(), "spxs", "cyfw"))) {
            TcCompany company = companyMapper.selectEntityById(Long.parseLong(checkInfo.get("COMPANY_ID").toString()));

            JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(checkId);
            //检查单今年的流水号
            if (checkInfo.get("RESULT_RECORD_INDEX") == null) {
                //当前单子未生成过.如果第二次保存结果记录表，则直接使用第一次的序号来生成
                JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
                dynamicScoring.setResultRecordIndex(resultTableSequence.getTableIndex());//加一并获取
                dynamicScoringMapper.updateById(dynamicScoring);
            }
            //序号按照6位数在签名补0
            Long index = dynamicScoring.getResultRecordIndex();
            String resultCode = SequenceService.generatorResultTableCode(company.getCompanyTypeCode(), index);
            checkInfo.put("resultCode", resultCode);
        }
        return checkInfo;
    }


    public String uploadResultRecord(Long checkId, MultipartFile imgFile, String type) throws Exception {
        JgDynamicScoring dynamicScoring = dynamicScoringMapper.selectById(checkId);
        if (imgFile != null && StringUtils.isNoneBlank(imgFile.getOriginalFilename())) {
            FileResultEntity fileResultEntity = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.inspect.getPath());
            if ("1".equals(type)) {
                dynamicScoring.setKeyPointsTableUrl(fileResultEntity.getFilePath());
            } else if ("2".equals(type)) {
                dynamicScoring.setCheckRecordTableUrl(fileResultEntity.getFilePath());
            }
            dynamicScoringMapper.updateById(dynamicScoring);
            return fileResultEntity.getFilePath();
        }
        return "";
    }

    /**
     * 查询风险等级确认表数据
     *
     * @param checkId
     * @return
     */
    public Map<String, Object> getRiskConfirmTable(Long checkId) throws Exception {
        JgRiskLevel riskLevel = riskLevelMapper.selectById(checkId);
        if (riskLevel == null) {
            return new HashMap<>();
        }
        TcCompany company = companyMapper.selectById(riskLevel.getCompanyId());
        if (company == null) {
            company = new TcCompany();
        }
        Long companyTypeId = company.getCompanyTypeId();
        Long companyTypeTwoId = company.getCompanyTypeTwoId();
        String companyType = "";
        if (StringUtils.equals(company.getSupProcess(), "cyfw")) {
            if (companyTypeId != null) {
                JgClassifyCyfw companyTypeFirst = classifyCyfwMapper.selectById(companyTypeId);
                companyType = companyTypeFirst.getName();
            }
            if (companyTypeTwoId != null) {
                JgClassifyCyfw companyTypeTwo = classifyCyfwMapper.selectById(companyTypeTwoId);
                companyType = companyType + " > " + companyTypeTwo.getName();
            }
        }
        if (StringUtils.equals(company.getSupProcess(), "spxs")) {
            if (companyTypeId != null) {
                JgClassifySpxs companyTypeFirst = classifySpxsMapper.selectById(companyTypeId);
                companyType = companyTypeFirst.getName();
            }
            if (companyTypeTwoId != null) {
                JgClassifySpxs companyTypeTwo = classifySpxsMapper.selectById(companyTypeTwoId);
                companyType = companyType + " > " + companyTypeTwo.getName();
            }
        }

        Map<String, Object> table = new HashMap<>();
        table.put("companyName", riskLevel.getCompanyName());
        table.put("companyAddress", company.getAddress());
        table.put("companyCompanyType", companyType);
        table.put("contactPhone", (company.getContact() == null ? "" : company.getContact()) + "-" + (company.getContactPhone() == null ? "" : company.getContactPhone()));
        //餐饮服务提供者  (  7-养老机构食堂  8-学校(含托幼机构)食堂  9-医疗机构食堂  11-中央厨房 12-集体用餐配送单位  10-工地食堂)
        StringBuffer tgz = new StringBuffer();
        if (companyTypeTwoId != null) {
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "7")) {
                tgz.append("√ 养老机构食堂  ");
            }
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "8")) {
                tgz.append("√ 学校(含托幼机构)食堂  ");
            }
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "9")) {
                tgz.append("√ 医疗机构食堂  ");
            }
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "10")) {
                tgz.append("√ 工地食堂  ");
            }
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "11")) {
                tgz.append("√ 中央厨房  ");
            }
            if (StringUtils.equals(String.valueOf(companyTypeTwoId), "12")) {
                tgz.append("√ 集体用餐配送单位  ");
            }
        }
        table.put("tgz", tgz.toString());

        //获取上一年风险等级
        Calendar calendar = Calendar.getInstance();
        int lastYear = calendar.get(Calendar.YEAR);
        QueryWrapper<JgRiskLevel> riskLevelEntity = new QueryWrapper();
        riskLevelEntity.eq("COMPANY_ID", riskLevel.getCompanyId());
        riskLevelEntity.eq("RISK_YEAR", lastYear - 1);
        List<JgRiskLevel> lastYearRiskLevelEntityList = riskLevelMapper.selectList(riskLevelEntity);
        if (!lastYearRiskLevelEntityList.isEmpty()) {
            table.put("lastYearRiskLevel", lastYearRiskLevelEntityList.get(0).getRiskLevel());
        }
        table.put("isXiaoyuan", StringUtils.equals(riskLevel.getIsXiaoyuan(), "1") ? "是" : "否");//使用页面提交的校园周边信息
        table.put("isGongpi", StringUtils.equals(riskLevel.getIsGongpi(), "1") ? "是" : "否");//使用页面提交的农批信息
        table.put("isFoodServicesSale", StringUtils.equals(company.getIsFoodServicesSale(), "1") ? "是" : "否");
        table.put("isFrozenFoodStorage", StringUtils.equals(company.getIsFrozenFoodStorage(), "1") ? "是" : "否");
        table.put("isFrozenFoodProducts", StringUtils.equals(company.getIsFrozenFoodProducts(), "1") ? "是" : "否");
        //是否因实施食品安全领域违法行为被列入严重违法失信名单
        Map<String, Object> jgDsjYzwfsxmd = jgDsjYzwfsxmdMapper.getLieYanByCreditCode(company.getCreditCode());
        if (jgDsjYzwfsxmd != null) {
            table.put("isLieyan", "是");
        } else {
            table.put("isLieyan", "否");
        }
        table.put("isShezuo", StringUtils.equals(company.getIsShezuo(), "1") ? "是" : "否");
        table.put("staticScore", riskLevel.getStaticScore());
        table.put("dynamicScore", riskLevel.getDynamicCheckScore());
        table.put("minusScore", riskLevel.getDynamicMinusScore());
        double sumD = DoubleUtil.sum(riskLevel.getStaticScore(), riskLevel.getDynamicCheckScore());
        double levelScore = DoubleUtil.sum(sumD, riskLevel.getDynamicMinusScore());
        table.put("score", levelScore);
        //spxs:食品销售环节
        if (company.getSupProcess().equals(PROCESS_SP)) {
            String riskBusiness = levelService.findRiskSaleBusiness(company, levelScore);
            table.put("scoreLevel", riskBusiness);
        } else if (company.getSupProcess().equals(PROCESS_CY)) {
            String riskBusiness = levelService.findRiskCateringBusiness(company, levelScore);
            table.put("scoreLevel", riskBusiness);
        }
        //动态调整
        List<JgRiskLevelDynamic> riskLevelList = riskLevelDynamicMapper.selectByRiskLevelId(riskLevel.getId());
        List<Map<String, Object>> contentList = new ArrayList<>();
        if (!riskLevelList.isEmpty()) {
            for (JgRiskLevelDynamic jgRiskLevelDynamic : riskLevelList) {
                Map<String, Object> content = new HashMap<>();
                content.put("title", jgRiskLevelDynamic.getReason());
                content.put("selection", jgRiskLevelDynamic.getSelection());
                contentList.add(content);
            }
        }
        table.put("contentList", contentList);
        table.put("riskLevel", riskLevel.getRiskLevel());
        return table;
    }

    public void updateRiskConfirmTable(Long checkId, MultipartFile imgFile) throws Exception {
        JgRiskLevel riskLevel = riskLevelMapper.selectById(checkId);
        FileResultEntity url = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.risk.getPath());
        riskLevel.setConfirmTable(url.getFilePath());
        riskLevel.setDeleteFlag(0);
        riskLevelMapper.updateById(riskLevel);
    }


}